﻿Imports System.Data
Imports System.Threading
Imports System.Threading.Tasks
Imports System.Collections.ObjectModel
Imports FuncClasses
Imports System.ComponentModel
Imports System.Xml
Imports FuncClasses.Bn.Classes
Imports System.Windows.Threading
Imports Microsoft.WindowsAPICodePack.Dialogs
Imports System.Windows.Media.Animation

''' <summary>
''' Repräsentiert die Klasse des Hauptarbeitsfensters
''' </summary>
''' <remarks></remarks>
Public Class Window1
    Implements INotifyPropertyChanged

#Region "Variables"
    Private ordervm As OrderViewModel
    Private articlevm As ArticleViewModel
    Private customervm As CustomerViewModel

    Private categoriesak As Category
    Private categoriesnl As Category

    Private suggestion As core.AutoCompleteManager

    Private GoToImport As Boolean = False

    Public WithEvents UpdateChecker As New UpdateProvider(Dispatcher)
    Private WithEvents loader As IDatabase

    Private currentLayout As ICustomLayout

    Private closechecker As Boolean = False

    Private settingsvm As VariousSettingsViewModel
    Private customerstatistic As FuncClasses.Statistics.CustomerStats
    Private companystats As FuncClasses.Statistics.CompanyStats
    Private articlestats As FuncClasses.Statistics.ArticleStats

    Private timer1 As New DispatcherTimer
    Private tablestyle As TableStyle

    Private addinmanager As AddInManager

    Private log As New Log
#End Region

#Region "Programmstart"
    Private isloading As Boolean = True
    ''' <summary>
    ''' Erstellt eine neue Instanz des Hauptarbeitsfensters
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub New()

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        FlyOuts.Visibility = Windows.Visibility.Visible

        '## XP Fix FlyOuts ##'
        If IsDwmEnabled = False Then
            FlyOuts.Margin = New Thickness(-4)
        End If
    End Sub

    Private Sub LoadBackstage()
        While True
            If BackStageFirmenWahl.Items.Item(1).Equals(BackStageSeperator) = False Then
                BackStageFirmenWahl.Items.RemoveAt(1)
            Else
                Exit While
            End If
        End While

        For Each item In loader.GetAllCompanys
            Dim tab As New BackstageCompanyItem(item.CompanyName, item)
            AddHandler tab.ChangeCompany, AddressOf PerformCompanyChange
            BackStageFirmenWahl.Items.Insert(1, tab)
        Next

        Dim etab As New TabItem
        etab.Header = "                                              "
        etab.IsEnabled = False
        etab.Visibility = Windows.Visibility.Hidden
        BackStageFirmenWahl.Items.Insert(BackStageFirmenWahl.Items.IndexOf(BackStageSeperator), etab)

        GenerateAddInList()
    End Sub

    Private Sub LoadSettings()
        SettingsItemAllg.DataContext = settingsvm
        TabItemTaxClass.DataContext = settingsvm
        cb_einheit.DataContext = settingsvm
        ComboBox9.DataContext = settingsvm
        ComboBox8.DataContext = settingsvm
        customereditcontrol.SetSettingsViewmodel(SettingsViewModel)
        customereditcontrol.SetUser(CurrentUser)
        customereditcontrol.SetDatabase(loader)

        '### Steuerbezeichnung ###'
        Dim bez As String = loader.TaxDescription
        If String.IsNullOrEmpty(bez) Then
            loader.TaxDescription = "mwst"
            bez = "mwst"
        End If
        If bez = "mwst" Then
            RadioButton4.IsChecked = True
        ElseIf bez = "ust" Then
            RadioButton5.IsChecked = True
        End If

        '### Aktuelles Datum beim Filter setzen ###'
        Dim datum As New Datum
        datum = datum.GetCurrentDate
        comboFilterMonat.SelectedIndex = datum.Monat - 1
        comboFilterJahr.SelectedValue = datum.Jahr.ToString
        buttonAuftragFiltern.IsChecked = True

        Dim ex As Boolean = False
        Dim today As New Datum(Date.Today)
        comboFilterJahr.DataContext = OrderViewModel
        comboFilterJahr.SelectedItem = today.Jahr.ToString

        '### Warnungen ###'
        Dim b As Boolean
        Try : b = loader.GetSettingByKey("AuftragDelete") : Catch : b = True : End Try
        ToggleButton1.IsChecked = b
        Try : b = loader.GetSettingByKey("ArticleDelete") : Catch : b = True : End Try
        ToggleButton2.IsChecked = b
        Try : b = loader.GetSettingByKey("CustomerDelete") : Catch : b = True : End Try
        ToggleButton3.IsChecked = b

        Dim savedtablestyle As Integer
        Try : savedtablestyle = CInt(loader.GetSettingByKey("tablestyle")) : Catch : savedtablestyle = 2 : End Try
        ComboBox1.SelectedIndex = savedtablestyle
    End Sub

    Private Sub LoadCategories()
        If TypeOf (loader) Is FastXML Then
            categoriesak = loader.GetCategories("Alle Kategorien", CurrentUser)
            categoriesnl = loader.GetCategories("Nebenleistungen", CurrentUser)
        Else
            categoriesak = loader.GetCategories("-Alle Kategorien", CurrentUser)
            categoriesnl = loader.GetCategories("-Nebenleistungen", CurrentUser)
        End If

        Try
            Dim categorycol As New ObservableCollection(Of UICategory)
            categorycol.Add(categoriesak.ToUICategory)
            categorycol.Add(categoriesnl.ToUICategory)

            TreeView1.ItemsSource = categorycol
            TreeView3.ItemsSource = categorycol
        Catch ex As Exception

        End Try
        
    End Sub

    Private Sub RibbonWindow_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        Me.Resources.MergedDictionaries.Add(Dictionaries.GetMainWindowLocalization)
        Me.WindowState = Windows.WindowState.Maximized
        Dim path As String = System.AppDomain.CurrentDomain.BaseDirectory() + "\database.xml"
        If IO.File.Exists(path) = False Then
            NewCompany.Visibility = Windows.Visibility.Visible
            WelcomeRight.Visibility = Windows.Visibility.Collapsed
            SPWelcomeLeft.Visibility = Windows.Visibility.Collapsed
        Else
            DatabaseSet()
        End If
    End Sub

    Private Sub DatabaseSet() Handles firstrunwizard.DatabaseSet, DBDisconnectControl.DBRetryRequest
        WaitDBControl.Visibility = Windows.Visibility.Visible
        DBDisconnectControl.Visibility = Windows.Visibility.Collapsed
        If firstrunwizard.Database Is Nothing Then
            Dim path As String = System.AppDomain.CurrentDomain.BaseDirectory() + "\database.xml"
            Dim doc = XElement.Load(path)
            If doc.Attribute("name").Value = "FastXML" Then
                loader = New FastXML(doc.Attribute("directory").Value)
            ElseIf doc.Attribute("name").Value = "SQLite" Then
                loader = New FluentNHibernateConnector(AppID, doc.Attribute("directory").Value, Dispatcher, doc.Attribute("name").Value)
            Else
                loader = New FluentNHibernateConnector(AppID, doc.Attribute("dbserver").Value, doc.Attribute("dbname").Value, doc.Attribute("dbuser").Value, doc.Attribute("dbuserpasswd").Value, Dispatcher, doc.Attribute("name").Value)
            End If
            AddHandler loader.DatabaseConnected, AddressOf DatabaseConnected
            AddHandler loader.DatabaseNotConnected, AddressOf DatabaseNotConnected
            loader.Connect()
        Else
            loader = firstrunwizard.Database
            DatabaseConnected(loader)
        End If
    End Sub

    Private Sub DBError(msg As String)
        MessageBox.Show(msg)
    End Sub

    Private Sub DatabaseNotConnected(db As IDatabase)
        DBDisconnectControl.Visibility = Windows.Visibility.Visible
        WaitDBControl.Visibility = Windows.Visibility.Collapsed
    End Sub

    Private Sub DatabaseConnected(db As IDatabase)
        DBDisconnectControl.Visibility = Windows.Visibility.Collapsed
        WaitDBControl.Visibility = Windows.Visibility.Collapsed
        AddHandler loader.UserRightsMissing, AddressOf MissingUserRights
        AddHandler loader.DatabaseError, AddressOf DBError
        If Not String.IsNullOrEmpty(firstrunwizard.CompanyName) Then
            NewCompany.Visibility = Windows.Visibility.Collapsed
            WelcomeRight.Visibility = Windows.Visibility.Visible
            SPWelcomeLeft.Visibility = Windows.Visibility.Visible
            HideFlyOuts()
        End If

        RegisterLayout()

        chart.DataContext = {New KeyValuePair(Of String, Money)("empty", New Money(0))}
        Dim rate As New RateApp(Me)
        Dim item As New NewYearsEve(Me)
        Dim news As New NewsControl(Me)

        If firstrunwizard.User IsNot Nothing Then
            loader.SetSettingByKey("lastuser", firstrunwizard.User.Name)
            LoggedIn(firstrunwizard.User)
        Else
            Dim userlogin As New LogInFrontPage(Me)
            AddHandler userlogin.LoginSucceed, AddressOf LoggedIn
        End If
    End Sub

    Private Sub LoggedIn(usr As User)
        _currentuser = usr
        If usr IsNot Nothing Then
            import = New CSVImport("", loader, Dispatcher, CurrentUser)
            AddHandler timer1.Tick, New eventhandler(AddressOf Timer_Tick)
            timer1.Interval = New TimeSpan(0, 0, 0, 0, 1)
            timer1.Start()
        End If
        addinmanager = New AddInManager(Dispatcher, Me, CurrentUser)
    End Sub

    Private Sub Timer_Tick(sender As Object, e As EventArgs)
        timer1.Stop()

        ' We need the size of chart control
        CustomerStatsTabItem.Visibility = Windows.Visibility.Visible
        TabControl1.SelectedItem = TabItem6
        KundeTabControl.SelectedItem = CustomerStatsTabItem
        TabControl1.SelectedIndex = 0
        CustomerStatsTabItem.Visibility = Windows.Visibility.Collapsed

        settingsvm = New VariousSettingsViewModel(loader, Dispatcher)

        Me.Title = "Biller - " + loader.LastCompany
        CurrentCompany.Content = loader.LastCompany

        ordervm = New OrderViewModel(loader, Dispatcher, CurrentUser)
        articlevm = New ArticleViewModel(loader, Dispatcher, CurrentUser)
        customervm = New CustomerViewModel(loader, Dispatcher, CurrentUser)
        usermanagementSettingspage.DataContext = New UserManagementViewModel(Dispatcher, CurrentUser, loader)

        LoadSettings()

        CompleteBoxes()

        LoadBackstage()

        LoadCategories()

        FillBackupListView()

        '### Erweiterungen ###'
        ListView3.DataContext = addinmanager.AddInList

        '### Artikel ###'
        ListView2.DataContext = articlevm

        '### Aufträge ###'
        ListView1.DataContext = ordervm

        '### Kunden ###'
        ListViewKunden.DataContext = customervm

        '### Firmendaten ###'
        Dim cs = loader.GetCompanySettings(loader.LastCompany)
        Label112.Content = cs.TaxID
        Label111.Content = cs.TradeID
        Dim a1 As Address = cs.ToAddress
        Label108.Content = cs.CompanyName
        Label109.Content = a1.Street + " " + a1.No
        Label110.Content = a1.ZipCode + " " + a1.City

        '### Zur Import Seite gehen ###'
        If GoToImport = True Then
            _ribbon.SelectedTabIndex = _ribbon.Tabs.IndexOf(TabVerwaltung)
            TabControl1.SelectedItem = TabItem8
        Else
            TabControl1.SelectedItem = TabItem1
        End If

        editcategory.SetAtricleViewModel(articlevm)
        editcategory.SetDatabase(loader)
        editcategory.SetTreeView(TreeView1)
        editcategory.SetUser(CurrentUser)

        UpdateChecker.AddFile(New UpdateFileInfo("Biller.exe", "Hauptprogramm", Version))

        Licenses()

        closechecker = True
        isloading = False

        customerstatistic = New FuncClasses.Statistics.CustomerStats(Dispatcher, loader, CurrentUser)
        AddHandler customerstatistic.GetMonthlySalesCompleted, AddressOf CustomerMonthlySalesCompleted
        AddHandler customerstatistic.GetMostBoughtArticlesCompleted, AddressOf MostBoughtArticlesofCustomerCompleted

        companystats = New FuncClasses.Statistics.CompanyStats(Dispatcher, loader, CurrentUser)
        AddHandler companystats.GetCustomerSalesListCompleted, AddressOf CustomerSalesListCompleted
        AddHandler companystats.GetMonthlySalesListCompleted, AddressOf MonthlySalesCompelted
        companystats.GetMonthlySalesAsync(New Date(Date.Today.AddMonths(-5).Year, Date.Today.AddMonths(-5).Month, 1), Date.Today)

        calendar.SelectedDate = Date.Today
        AddHandler calendar.SelectedDatesChanged, AddressOf Calendar1_SelectedDatesChanged


        articlestats = New FuncClasses.Statistics.ArticleStats(Dispatcher, loader, CurrentUser)
        AddHandler articlestats.GetMostBoughtArticlesCompleted, AddressOf GetMostBoughtArticlesCompleted

        '### Load Temp Orders, Customers, Articles ###'
        If loader.SupportsTemporaryItems Then
            For Each auf As Order In loader.LoadTempOrders(CurrentUser)
                LoadOrder(auf)
            Next
        End If

        Try
            ToggleButton4.IsChecked = CBool(loader.GetSettingByKey("AutoBackupPathEnabled"))
        Catch ex As Exception
            ToggleButton4.IsChecked = True
        End Try
        TBBackupPath.Text = BackUpDirectory
        'NotifyPropertyChanged("")
        FlyOuts.DataContext = Me
        BackStageMenu.DataContext = Me
        TabItem8.DataContext = import
    End Sub

    Private Sub MonthlySalesCompelted(result As Collection(Of DateValueModel))
        chart2.DataContext = result
    End Sub

    Private Sub Licenses()
        AddNewLicense("Fluent Ribbon Control Suite", "Microsoft Public License (Ms-PL)", My.Resources.mspl)
        AddNewLicense("Crystal Project (Icons)", "GNU General Public License", My.Resources.lgpl)
    End Sub

    Private Sub CompleteBoxes()
        'suggestion = New core.AutoCompleteManager(TextBox19)
        'suggestion.Asynchronous = True
        'suggestion.ShowPopupOnFocus = True
        'suggestion.AutoAppend = True
    End Sub
#End Region

#Region "Tab Aufträge"
    Private workingonauftrag As Boolean = False
    Private FormOfArticleRequest As KeyValuePairs
    ''' <summary>
    ''' Beinhaltet alle offnen Auftrag-Tabs
    ''' </summary>
    ''' <remarks>Key beinhaltet das AuftragRibbon-Control, Value das AuftragControl-Control</remarks>
    Dim AuftragControlHolder As New Collection(Of KeyValuePairs)

    Private Sub buttonNeuerAuftrag_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonNeuerAuftrag.Click
        Dim auftrag As Order = New Order(ordervm.AllOrders)
        auftrag.OrderID = (GetNumberforOrder(auftrag.DokumentArt))
        Dim ribbontab As New AuftragRibbon(Me)
        Dim tabitemAuftrag As New AuftragControl(auftrag, loader, ribbontab, SettingsViewModel, OrderViewModel, Me, CurrentUser)
        AuftragControlHolder.Add(New KeyValuePairs(ribbontab, tabitemAuftrag))
        ribbontab.Header = "Neuer Auftrag"
        If AuftragControlHolder.Count > 1 Then
            AuftragContextGroup.Header = "Aufträge"
        End If
        AuftragContextGroup.Visibility = Windows.Visibility.Visible
        ribbontab.Group = AuftragContextGroup
        _ribbon.Tabs.Insert(IndexofLastAuftragRibbonTab, ribbontab)
        _ribbon.SelectedTabItem = ribbontab
        TabControl1.Items.Add(tabitemAuftrag)
        AddHandler ribbontab.Abort, AddressOf RibbonAuftragClose
        AddHandler ribbontab.SaveAndExit, AddressOf RibbonAuftragClose
        AddHandler ribbontab.PrintPDF, AddressOf PrintAuftrag
        AddHandler ribbontab.SavePDF, AddressOf SaveAuftrag
        AddHandler ribbontab.RequestArticle, AddressOf ShowFormForRequestedArticle
        AddHandler ribbontab.UserWantToChooseCustomer, AddressOf ShowFormForCustomerRequest
        AddHandler tabitemAuftrag.UserWantToChooseCustomer, AddressOf ShowFormForCustomerRequest
        AddHandler tabitemAuftrag.furtherorder, AddressOf WeitergefuehrterAuftrag

        For Each plugin In addinmanager.AddInList
            plugin.NewOrderControl(tabitemAuftrag)
        Next
        OrderFlyOut.IsOpen = False
        RaiseEvent NewOrder(auftrag)
    End Sub

    Private Sub buttonAuftragBearbeiten_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonAuftragBearbeiten.Click
        If ListView1.SelectedItems.Count = 1 Then
            Dim item As OrderPreviewModel = ListView1.SelectedItem
            LoadOrder(loader.GetOrder(item.OrderID, item.OrderTyp, CurrentUser))
        End If
    End Sub

    Public Sub LoadOrder(ByVal auftrag As Order)
        Dim ribbontab As New AuftragRibbon(Me)
        Dim tabitemAuftrag As New AuftragControl(auftrag, loader, ribbontab, SettingsViewModel, OrderViewModel, Me, CurrentUser)
        AuftragControlHolder.Add(New KeyValuePairs(ribbontab, tabitemAuftrag))
        If Customer.IsEmpty(auftrag.Customer) = False Then
            ribbontab.Header = auftrag.Customer.DisplayName
        Else
            ribbontab.Header = "Neuer Auftrag"
        End If
        If AuftragControlHolder.Count > 1 Then
            AuftragContextGroup.Header = "Aufträge"
        End If
        AuftragContextGroup.Visibility = Windows.Visibility.Visible
        ribbontab.Group = AuftragContextGroup
        _ribbon.Tabs.Insert(IndexofLastAuftragRibbonTab, ribbontab)
        _ribbon.SelectedTabItem = ribbontab
        TabControl1.Items.Add(tabitemAuftrag)
        AddHandler ribbontab.Abort, AddressOf RibbonAuftragClose
        AddHandler ribbontab.SaveAndExit, AddressOf RibbonAuftragClose
        AddHandler ribbontab.PrintPDF, AddressOf PrintAuftrag
        AddHandler ribbontab.SavePDF, AddressOf SaveAuftrag
        AddHandler ribbontab.RequestArticle, AddressOf ShowFormForRequestedArticle
        AddHandler ribbontab.UserWantToChooseCustomer, AddressOf ShowFormForCustomerRequest
        AddHandler tabitemAuftrag.UserWantToChooseCustomer, AddressOf ShowFormForCustomerRequest
        AddHandler tabitemAuftrag.furtherorder, AddressOf WeitergefuehrterAuftrag

        For Each plugin In addinmanager.AddInList
            plugin.NewOrderControl(tabitemAuftrag)
        Next
        OrderFlyOut.IsOpen = False
        RaiseEvent OrderLoaded(auftrag)
    End Sub

    Private Function GetNumberforOrder(dokuart As Dokumentart) As String
        Dim auftrag As Order
        Select Case dokuart
            Case Dokumentart.Angebot
                auftrag = New Order(ordervm.AllOrders, Dokumentart.Angebot)
                For Each kvp As KeyValuePairs In AuftragControlHolder
                    Dim c As AuftragControl = kvp.Value
                    If c.CompleteAuftrag.DokumentArt = Dokumentart.Angebot Then
                        If c.CompleteAuftrag.OrderID >= auftrag.OrderID Then
                            auftrag.OrderID = (c.CompleteAuftrag.OrderID + 1)
                        End If
                    End If
                Next
                Return auftrag.OrderID
            Case Dokumentart.Gutschrift
                auftrag = New Order(ordervm.AllOrders, Dokumentart.Gutschrift)
                For Each kvp As KeyValuePairs In AuftragControlHolder
                    Dim c As AuftragControl = kvp.Value
                    If c.CompleteAuftrag.DokumentArt = Dokumentart.Gutschrift Then
                        If c.CompleteAuftrag.OrderID >= auftrag.OrderID Then
                            auftrag.OrderID = (c.CompleteAuftrag.OrderID + 1)
                        End If
                    End If
                Next
                Return auftrag.OrderID
            Case Dokumentart.Lieferschein
                auftrag = New Order(ordervm.AllOrders, Dokumentart.Lieferschein)
                For Each kvp As KeyValuePairs In AuftragControlHolder
                    Dim c As AuftragControl = kvp.Value
                    If c.CompleteAuftrag.DokumentArt = Dokumentart.Lieferschein Then
                        If c.CompleteAuftrag.OrderID >= auftrag.OrderID Then
                            auftrag.OrderID = (c.CompleteAuftrag.OrderID + 1)
                        End If
                    End If
                Next
                Return auftrag.OrderID
            Case Dokumentart.Rechnung
                auftrag = New Order(ordervm.AllOrders, Dokumentart.Rechnung)
                For Each kvp As KeyValuePairs In AuftragControlHolder
                    Dim c As AuftragControl = kvp.Value
                    If c.CompleteAuftrag.DokumentArt = Dokumentart.Rechnung Then
                        If c.CompleteAuftrag.OrderID >= auftrag.OrderID Then
                            auftrag.OrderID = (c.CompleteAuftrag.OrderID + 1)
                        End If
                    End If
                Next
                Return auftrag.OrderID
        End Select
    End Function

    Private Sub WeitergefuehrterAuftrag(ByVal auf As Order, target As Dokumentart)
        Dim auftrag As Order = loader.GetOrder(auf.OrderID, auf.DokumentArt, CurrentUser)
        If auftrag IsNot Nothing Then
            auftrag.DokumentArt = target
            auftrag.OrderID = (GetNumberforOrder(auftrag.DokumentArt))
            Select Case target
                Case Dokumentart.Angebot
                    auf.LinkedToOffer = auftrag.OrderID
                Case Dokumentart.Gutschrift
                    auf.LinkedToCredit = auftrag.OrderID
                Case Dokumentart.Lieferschein
                    auf.LinkedToDelivery = auftrag.OrderID
                Case Dokumentart.Rechnung
                    auf.LinkedToInvoice = auftrag.OrderID
            End Select
            ordervm.SaveOrder(auf)

            Select Case auf.DokumentArt
                Case Dokumentart.Angebot
                    auftrag.LinkedFromOffer = auf.OrderID
                Case Dokumentart.Gutschrift
                    auftrag.LinkedFromCredit = auf.OrderID
                Case Dokumentart.Lieferschein
                    auftrag.LinkedFromDelivery = auf.OrderID
                Case Dokumentart.Rechnung
                    auftrag.LinkedFromInvoice = auf.OrderID
            End Select

            Dim ribbontab As New AuftragRibbon(Me)
            Dim tabitemAuftrag As New AuftragControl(auftrag, loader, ribbontab, SettingsViewModel, OrderViewModel, Me, CurrentUser)
            AuftragControlHolder.Add(New KeyValuePairs(ribbontab, tabitemAuftrag))
            If Customer.IsEmpty(auftrag.Customer) Then : ribbontab.Header = "Kein Kunde festgelegt" : Else : ribbontab.Header = auftrag.Customer.DisplayName : End If

            If AuftragControlHolder.Count > 1 Then
                AuftragContextGroup.Header = "Aufträge"
            End If

            AuftragContextGroup.Visibility = Windows.Visibility.Visible
            ribbontab.Group = AuftragContextGroup
            _ribbon.Tabs.Insert(IndexofLastAuftragRibbonTab, ribbontab)
            _ribbon.SelectedTabItem = ribbontab
            TabControl1.Items.Add(tabitemAuftrag)

            '### Eventhandler ###'
            AddHandler ribbontab.Abort, AddressOf RibbonAuftragClose
            AddHandler ribbontab.SaveAndExit, AddressOf RibbonAuftragClose
            AddHandler ribbontab.PrintPDF, AddressOf PrintAuftrag
            AddHandler ribbontab.SavePDF, AddressOf SaveAuftrag
            AddHandler ribbontab.RequestArticle, AddressOf ShowFormForRequestedArticle
            AddHandler ribbontab.UserWantToChooseCustomer, AddressOf ShowFormForCustomerRequest
            AddHandler tabitemAuftrag.UserWantToChooseCustomer, AddressOf ShowFormForCustomerRequest
            AddHandler tabitemAuftrag.furtherorder, AddressOf WeitergefuehrterAuftrag

            For Each plugin In addinmanager.AddInList
                plugin.NewOrderControl(tabitemAuftrag)
            Next
            RaiseEvent OrderLoaded(auftrag)
        Else
            If TaskDialog.IsPlatformSupported Then
                Dim td As New TaskDialog()
                td.Cancelable = True
                td.Icon = TaskDialogStandardIcon.Error
                td.Caption = "Auftrag weiterführen"
                td.InstructionText = "Speichern Sie den Auftrag, bevor Sie ihn weiterführen."
                td.Text = "Es ist nicht möglich, einen ungespeicherten Auftrag weiterzuführen. Klicken Sie auf Ok und speichern Sie den Auftrag."
                td.StandardButtons = TaskDialogStandardButtons.Ok
                td.Show()
            Else
                PSTaskDialog.cTaskDialog.ForceEmulationMode = True
                PSTaskDialog.cTaskDialog.EmulatedFormWidth = 450
                PSTaskDialog.cTaskDialog.MessageBox("Auftrag weiterführen", "Speichern Sie den Auftrag, bevor Sie ihn weiterführen.", "Es ist nicht möglich, einen ungespeicherten Auftrag weiterzuführen. Klicken Sie auf Ok und speichern Sie den Auftrag.", PSTaskDialog.eTaskDialogButtons.OK, PSTaskDialog.eSysIcons.Error)
            End If
        End If
    End Sub

    Private Sub RibbonAuftragClose(source As AuftragRibbon)
        RemoveHandler source.Abort, AddressOf RibbonAuftragClose
        RemoveHandler source.SaveAndExit, AddressOf RibbonAuftragClose
        RemoveHandler source.PrintPDF, AddressOf PrintAuftrag
        RemoveHandler source.SavePDF, AddressOf SaveAuftrag
        RemoveHandler source.UserWantToChooseCustomer, AddressOf ShowFormForCustomerRequest
        RemoveHandler source.RequestArticle, AddressOf ShowFormForRequestedArticle

        For Each kvp As KeyValuePairs In AuftragControlHolder
            If kvp.Key.Equals(source) Then
                _ribbon.SelectedTabIndex = 0
                Dim group As Fluent.RibbonContextualTabGroup = _ribbon.ContextualGroups.Item(0)
                group.Items.Remove(source)
                Dim i As Fluent.RibbonTabItem = kvp.Key
                i.Visibility = Windows.Visibility.Collapsed
                _ribbon.Tabs.Remove(kvp.Key)
                TabControl1.Items.Remove(kvp.Value)
                AuftragControlHolder.Remove(kvp)
                If AuftragControlHolder.Count = 1 Then
                    AuftragContextGroup.Header = "  Auftrag bearbeiten  "
                End If
                Exit Sub
            End If
        Next
    End Sub

    Function IndexofLastAuftragRibbonTab() As Integer
        Dim tmp As Integer = IndexOfLastNormalRibbonTab()
        For Each tab As Fluent.RibbonTabItem In _ribbon.Tabs
            Try
                If tab.Group.Equals(AuftragContextGroup) Then
                    tmp += 1
                End If
            Catch ex As Exception : End Try
        Next
        Return tmp
    End Function

    Function IndexOfLastNormalRibbonTab() As Integer
        Dim tmp As Integer = 0
        For Each tab As Fluent.RibbonTabItem In _ribbon.Tabs
            Try
                If tab.Group Is Nothing Then
                    tmp += 1
                End If
            Catch ex As Exception : End Try
        Next
        Return tmp
    End Function

    Private Sub buttonAuftragLoeschen_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonAuftragLoeschen.Click
        OrderDeleteRequest(ListView1.SelectedItem)
    End Sub

    Private Sub buttonAuftragFiltern_Unchecked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonAuftragFiltern.Unchecked
        buttonAuftragFiltern.IsChecked = True
    End Sub

    Private Sub comboFilterMonat_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles comboFilterMonat.SelectionChanged
        If isloading = False Then
            Try
                If comboFilterJahr.SelectedItem.ToString = Nothing Then
                    buttonAuftragFiltern.IsEnabled = False
                Else
                    If comboFilterMonat.SelectedItem.ToString = Nothing Then
                    Else
                        buttonAuftragFiltern.IsEnabled = True
                    End If
                End If
                If buttonAuftragFiltern.IsChecked = True Then
                    FilterOrders()
                End If
            Catch ex As Exception : End Try
        End If
    End Sub

    Private Sub comboFilterJahr_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles comboFilterJahr.SelectionChanged
        Try
            If comboFilterJahr.SelectedItem.ToString = Nothing Then
                buttonAuftragFiltern.IsEnabled = False
            Else
                If comboFilterMonat.SelectedItem.ToString = Nothing Then
                Else
                    buttonAuftragFiltern.IsEnabled = True
                End If
            End If
            If buttonAuftragFiltern.IsChecked = True Then
                FilterOrders()
            End If
        Catch ex As Exception : End Try
    End Sub

    Private Sub FilterOrders()
        ordervm.SetMonthlyInterval(comboFilterJahr.SelectedValue, comboFilterMonat.SelectedIndex + 1)
    End Sub

    ''' <summary>
    ''' Aufträge nur im gewählten Jahr und Monat anzeigen
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub buttonAuftragFiltern_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonAuftragFiltern.Checked
        FilterOrders()
    End Sub

    Private Sub ListView1_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles ListView1.SelectionChanged
        If ListView1.SelectedItems.Count > 0 Then
            buttonAuftragBearbeiten.IsEnabled = True
            buttonAuftragLoeschen.IsEnabled = True
            buttonAuftragPDF.IsEnabled = True
            buttonAuftragDrucken.IsEnabled = True
        Else
            buttonAuftragBearbeiten.IsEnabled = False
            buttonAuftragLoeschen.IsEnabled = False
            buttonAuftragPDF.IsEnabled = False
            buttonAuftragDrucken.IsEnabled = False
        End If
    End Sub

    Private Sub ListView1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles ListView1.MouseDoubleClick
        If ListView1.SelectedItems.Count = 1 Then
            Dim auftrag As OrderPreviewModel = ListView1.SelectedItem
            LoadOrder(loader.GetOrder(auftrag.OrderID, auftrag.OrderTyp, CurrentUser))
        End If
    End Sub

    Private Sub ListView1_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles ListView1.KeyUp
        If e.Key = Key.Delete Then
            OrderDeleteRequest(ListView1.SelectedItem)
        End If
    End Sub

    Private Sub OrderDeleteRequest(order As OrderPreviewModel)
        Dim result As Forms.DialogResult
        Dim b As Boolean = ToggleButton1.IsChecked
        If b = True Then
            If TaskDialog.IsPlatformSupported Then
                Dim td As New TaskDialog()
                td.Cancelable = True
                td.Icon = TaskDialogStandardIcon.Shield
                td.Caption = "Auftrag löschen?"
                td.InstructionText = "Wollen sie diesen Auftrag wirklich löschen?"
                td.Text = "Der gelöschte Auftrag kann nicht wiederhergestellt werden und wird in keiner Statistik mehr berücksichtigt."
                td.StandardButtons = TaskDialogStandardButtons.Yes Or TaskDialogStandardButtons.No
                td.FooterCheckBoxChecked = b
                td.FooterCheckBoxText = "Meldung jedes mal zeigen."
                If td.Show() = TaskDialogResult.Yes Then
                    result = Forms.DialogResult.Yes
                Else
                    result = Forms.DialogResult.No
                End If
                ToggleButton1.IsChecked = td.FooterCheckBoxChecked
            Else
                PSTaskDialog.cTaskDialog.ForceEmulationMode = True
                PSTaskDialog.cTaskDialog.EmulatedFormWidth = 450
                result = PSTaskDialog.cTaskDialog.MessageBox("Auftrag löschen?", "Wollen sie diesen Auftrag wirklich löschen?", "Der gelöschte Auftrag kann nicht wiederhergestellt werden und wird in keiner Statistik mehr berücksichtigt.", PSTaskDialog.eTaskDialogButtons.YesNo, PSTaskDialog.eSysIcons.Warning)
            End If
        Else
            result = Forms.DialogResult.Yes
        End If

        If result = Forms.DialogResult.Yes Then
            loader.DeleteOrder(order.OrderID, order.OrderTyp, CurrentUser)
            ordervm.Refresh()
            FilterOrders()
        End If
    End Sub

    Private Sub buttonAuftragPDF_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonAuftragPDF.Click
        Dim order As Order = Database.GetOrder(CType(ListView1.SelectedItem, OrderPreviewModel).OrderID, CType(ListView1.SelectedItem, OrderPreviewModel).OrderTyp, CurrentUser)
        ' Configure open file dialog box
        Dim dlg As New System.Windows.Forms.SaveFileDialog()
        dlg.Title = "PDF Speichern"
        dlg.FileName = order.DokumentArt.ToString + " Nr. " + order.OrderID.ToString
        dlg.DefaultExt = ".pdf" ' Default file extension
        dlg.Filter = "PDF Dokument |*.pdf" ' Filter files by extension

        ' Process open file dialog box results
        If dlg.ShowDialog() = Forms.DialogResult.OK Then
            Try
                currentLayout.Save(order, dlg.FileName)
            Catch ex As Exception
                MessageBox.Show("Es ist ein Fehler bei der Verarbeitung aufgetreten. Versuchen sie es nochmal.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error)
                log.AddEntry(ex.ToString)
            End Try
        End If
    End Sub

    Private Sub buttonAuftragDrucken_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles buttonAuftragDrucken.Click
        Dim auf As Order = Database.GetOrder(CType(ListView1.SelectedItem, OrderPreviewModel).OrderID, CType(ListView1.SelectedItem, OrderPreviewModel).OrderTyp, CurrentUser)
        Try
            currentLayout.Print(auf)
        Catch ex As Exception
            MessageBox.Show("Es ist ein Fehler bei der Verarbeitung aufgetreten. Versuchen sie es nochmal.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error)
            log.AddEntry(ex.ToString)
        End Try
    End Sub

    Private Sub buttonOrderSearch_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles buttonOrderSearch.Click
        OrderFlyOut.IsOpen = Not OrderFlyOut.IsOpen
    End Sub

    Private Sub TextBox2_KeyDown(sender As System.Object, e As System.Windows.Input.KeyEventArgs) Handles FlyOutOrderTB.KeyDown
        If e.Key = Key.Enter Then
            Dim art As Dokumentart
            If CBInvoice.IsChecked Then
                art = Dokumentart.Rechnung
            End If
            If CBOffer.IsChecked Then
                art = Dokumentart.Angebot
            End If
            If CBCredit.IsChecked Then
                art = Dokumentart.Gutschrift
            End If
            If CBDelivery.IsChecked Then
                art = Dokumentart.Lieferschein
            End If
            If loader.OrderExists(FlyOutOrderTB.Text, art, CurrentUser) Then
                LoadOrder(loader.GetOrder(FlyOutOrderTB.Text, art, CurrentUser))
            Else
                FlyOutOrderNotFound.Visibility = Windows.Visibility.Visible
            End If
        End If
    End Sub
#End Region

#Region "Contexttab Auftrag erstellen/bearbeiten"
    Private Sub PrintAuftrag(src As AuftragRibbon)
        For Each kvp As KeyValuePairs In AuftragControlHolder
            If kvp.Key.Equals(src) Then
                Dim temp As AuftragControl = kvp.Value
                currentLayout.Print(temp.CompleteAuftrag)
            End If
        Next
    End Sub

    Private Sub SaveAuftrag(path As String, src As AuftragRibbon)
        For Each kvp As KeyValuePairs In AuftragControlHolder
            If kvp.Key.Equals(src) Then
                Dim temp As AuftragControl = kvp.Value
                currentLayout.Save(temp.CompleteAuftrag, path)
            End If
        Next
    End Sub

    ''' <summary>
    ''' Returns a new invoice number for the specificed document type
    ''' </summary>
    ''' <param name="dokumentart">Document type for the new number</param>
    ''' <returns></returns>
    ''' <remarks>This function also considering the open and unsaved invoices</remarks>
    Public Function NewAuftragsNumber(ByVal dokumentart As Dokumentart)
        Dim auftrag As New Order(ordervm.AllOrders, dokumentart)
        Return auftrag.OrderID
    End Function

    ''' <summary>
    ''' This methode is called by the AuftragControl after saving the invoice
    ''' </summary>
    ''' <param name="auf"></param>
    ''' <remarks></remarks>
    Public Sub ReceiveAuftragDataForListView(auf As Order)
        RaiseEvent OrderSaved(auf)
    End Sub

    Private Sub ShowFormForRequestedArticle(source As AuftragRibbon)
        chooseArticelforAuftrag = True
        TabControl1.SelectedItem = TabItem2
        For Each kvp As KeyValuePairs In AuftragControlHolder
            If kvp.Key.Equals(source) Then
                FormOfArticleRequest = kvp
                Exit For
            End If
        Next
    End Sub

    Private Sub ShowFormForCustomerRequest(source As AuftragRibbon)
        chooseCustomerforAuftrag = True
        TabControl1.SelectedItem = TabItem5
        For Each kvp As KeyValuePairs In AuftragControlHolder
            If kvp.Key.Equals(source) Then
                FormOfArticleRequest = kvp
                Exit For
            End If
        Next
    End Sub

    Private Sub SendRequestedCustomer(CustNr As String)
        Dim temp As AuftragControl = FormOfArticleRequest.Value
        temp.AddRequestedCustomer(CustNr)
        TabControl1.SelectedItem = temp
    End Sub
#End Region

    Private Sub _ribbon_SelectedTabChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles _ribbon.SelectedTabChanged
        If _ribbon.SelectedTabItem IsNot Nothing Then
            Select Case _ribbon.SelectedTabItem.Name
                Case TabAuftrag.Name
                    TabControl1.SelectedItem = TabItem1
                    Exit Sub
                Case TabArtikel.Name
                    TabControl1.SelectedItem = TabItem2
                    chooseArticelforAuftrag = False
                    Exit Sub
                Case TabArtikelNeu.Name
                    TabControl1.SelectedItem = TabItem3
                    Exit Sub
                Case TabKunde.Name
                    TabControl1.SelectedItem = TabItem5
                    CustomerOverView.Visibility = Windows.Visibility.Visible
                    CustomerSalesListGrid.Visibility = Windows.Visibility.Collapsed
                    Exit Sub
                Case TabKundeNeu.Name
                    TabControl1.SelectedItem = TabItem6
                    Exit Sub
                Case TabVerwaltung.Name
                    TabControl1.SelectedItem = TabItem7
                    Exit Sub
                Case TabUpdate.Name
                    TabControl1.SelectedItem = TabItem10
                    Exit Sub
                Case TabStats.Name
                    If statscomingfrom IsNot Nothing Then
                        TabControl1.SelectedItem = TabItem5
                        Select Case statscomingfrom.Name
                            Case TabKunde.Name
                                CustomerOverView.Visibility = Windows.Visibility.Collapsed
                                CustomerSalesListGrid.Visibility = Windows.Visibility.Visible
                            Case TabArtikel.Name
                                TabControl1.SelectedItem = TabItemArticleStats
                        End Select
                    End If
            End Select

            For Each kvp As KeyValuePairs In addinribbons
                Dim r As Fluent.RibbonTabItem = kvp.Key
                If _ribbon.SelectedTabItem.Equals(r) AndAlso kvp.Value IsNot Nothing Then
                    TabControl1.SelectedItem = kvp.Value
                    Exit Sub
                End If
            Next

            For Each kvp As KeyValuePairs In AuftragControlHolder
                Dim r As Fluent.RibbonTabItem = kvp.Key
                If _ribbon.SelectedTabItem.Equals(r) Then
                    TabControl1.SelectedItem = kvp.Value
                    Exit Sub
                End If
            Next
        End If

    End Sub

#Region "Tab Article"
    Private chooseArticelforAuftrag As Boolean = False
    Private Sub buttonNeuerArtikel_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonNeuerArtikel.Click
        ArtikelContextGroup.Header = "Artikel anlegen"
        ArtikeldatenTabItem.Header = "Neuer Artikel"
        ArtikelContextGroup.Visibility = Windows.Visibility.Visible
        _ribbon.SelectedTabItem = TabArtikelNeu
        ArtikeldatenTabItem.DataContext = New Article()
        TabArtikel.IsEnabled = False
        BackStageMenu.IsEnabled = False
        ArtikelVorlageGroupBox.Visibility = Windows.Visibility.Visible
        tb_artnr.IsEnabled = True
        TabControl1.SelectedItem = TabItem3
        'RaiseEvent NewArtice()
    End Sub

    ''' <summary>
    ''' Artikel suchen
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub SearchTextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles SearchTextBox1.TextChanged
        ArtikelSuche()
    End Sub

    Private Sub ArtikelSuche()
        articlevm.SearchPattern = SearchTextBox1.Text.ToLower
    End Sub

    Private Sub ListView2_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles ListView2.SelectionChanged
        If ListView2.SelectedItems.Count = 1 Then
            buttonArtikelBearbeiten.IsEnabled = True
            buttonArtikelloeschen.IsEnabled = True
        Else
            buttonArtikelBearbeiten.IsEnabled = False
            buttonArtikelloeschen.IsEnabled = False
        End If
    End Sub

    Private Sub buttonArtikelloeschen_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonArtikelloeschen.Click
        ArticleDeleteRequest(ListView2.SelectedItem)
    End Sub

    Private Sub ArticleDeleteRequest(article As ArticlePreviewModel)
        Dim b As Boolean = ToggleButton2.IsChecked
        Dim result As Forms.DialogResult
        If b = True Then
            If TaskDialog.IsPlatformSupported Then
                Dim td As New TaskDialog()
                td.Cancelable = True
                td.Icon = TaskDialogStandardIcon.Shield
                td.Caption = "Artikel löschen?"
                td.InstructionText = "Wollen sie diesen Artikel wirklich löschen?"
                td.Text = "In Aufträgen, die diesen Artikel verwenden, können dann Artikelbezeichnung und andere Informationen nicht mehr angezeigt werden!"
                td.StandardButtons = TaskDialogStandardButtons.Yes Or TaskDialogStandardButtons.No

                td.FooterCheckBoxChecked = b
                td.FooterCheckBoxText = "Meldung jedes mal zeigen."
                If td.Show() = TaskDialogResult.Yes Then
                    result = Forms.DialogResult.Yes
                Else
                    result = Forms.DialogResult.No
                End If
                ToggleButton2.IsChecked = td.FooterCheckBoxChecked
            Else
                PSTaskDialog.cTaskDialog.ForceEmulationMode = True
                PSTaskDialog.cTaskDialog.EmulatedFormWidth = 450
                result = PSTaskDialog.cTaskDialog.MessageBox("Artikel löschen?", "Wollen sie diesen Artikel wirklich löschen?", "In Aufträgen, die diesen Artikel verwenden, können dann Artikelbezeichnung und andere Informationen nicht mehr angezeigt werden!", PSTaskDialog.eTaskDialogButtons.YesNo, PSTaskDialog.eSysIcons.Warning)
            End If
        Else
            result = Forms.DialogResult.Yes
        End If

        If result = Forms.DialogResult.Yes Then
            loader.DeleteArticle(article.ArticleID, CurrentUser)
            articlevm.Refresh()
        End If
    End Sub

    Private Sub ListView2_PreviewMouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles ListView2.PreviewMouseDoubleClick
        If ListView2.SelectedItems.Count = 1 Then
            If chooseArticelforAuftrag = False Then
                '### Den Tab öffnen ###'
                If _ribbon.SelectedTabItem.Name = TabArtikel.Name Then
                    ArtikelContextGroup.Header = "Artikel bearbeiten"
                    ArtikeldatenTabItem.Header = "Artikel bearbeiten"
                    ArtikelContextGroup.Visibility = Windows.Visibility.Visible
                    _ribbon.SelectedTabItem = TabArtikelNeu
                    TabArtikel.IsEnabled = False
                    BackStageMenu.IsEnabled = False
                End If
                TabControl1.SelectedItem = TabItem3
                '### Die Artikeldaten eintragen ###'
                Dim article As ArticlePreviewModel = ListView2.SelectedItem
                ArtikelDatenWeitergeben(loader.GetArticle(article.ArticleID, CurrentUser))
            Else
                Dim temp As AuftragControl = FormOfArticleRequest.Value
                Dim item As ArticlePreviewModel = ListView2.SelectedItem
                temp.AddRequestedArticle(loader.GetArticle(item.ArticleID, CurrentUser))
                TabControl1.SelectedItem = temp
                chooseArticelforAuftrag = False
            End If
        End If
    End Sub

    Private Sub ArtikelDatenWeitergeben(ByVal art As Article)
        Dim artikel As Article = art
        tb_artnr.IsEnabled = True
        ArtikelVorlageGroupBox.Visibility = Windows.Visibility.Visible
        ArtikeldatenTabItem.DataContext = artikel
        cb_einheit.SelectedIndex = cb_einheit.Items.IndexOf(artikel.ArticleUnit)
        ComboBox9.SelectedIndex = ComboBox9.Items.IndexOf(artikel.TaxClass)

        ComboBox3.SelectedIndex = Math.Abs(CInt(artikel.ArticlePrice1.IsGross))
        ComboBox4.SelectedIndex = Math.Abs(CInt(artikel.ArticlePrice2.IsGross))
        ComboBox5.SelectedIndex = Math.Abs(CInt(artikel.ArticlePrice3.IsGross))

        '### Kategorie ###'
        If String.IsNullOrEmpty(artikel.ArticleCategory) Then
            TreeView3.Items(0).IsSelected = True
        Else
            For Each sitem In TreeView3.Items
                If artikel.ArticleCategory.StartsWith("/" + sitem.Name) Then
                    artikel.ArticleCategory = Mid(artikel.ArticleCategory, 2)
                    sitem.IsExpanded = True
                    SetSelectedItem(sitem, artikel.ArticleCategory)
                End If
            Next
        End If
        tb_artnr.Foreground = tb_artbez.Foreground
        RaiseEvent ArticleLoaded(artikel)
    End Sub

    Private Sub SetSelectedItem(ByVal item As UICategory, phrase As String)
        'We have to cut the string
        phrase = Mid(phrase, phrase.IndexOf("/") + 2)
        If item.Name = phrase Then
            item.IsSelected = True
        Else
            For Each sitem In item.Children
                If phrase.StartsWith(sitem.Name) Then
                    sitem.IsExpanded = True
                    SetSelectedItem(sitem, phrase)
                End If
            Next
        End If
    End Sub

    Private Sub buttonArtikelBearbeiten_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonArtikelBearbeiten.Click
        '### Den Tab öffnen ###'
        ArtikelContextGroup.Header = "Artikel bearbeiten"
        ArtikeldatenTabItem.Header = "Artikel bearbeiten"
        ArtikelContextGroup.Visibility = Windows.Visibility.Visible
        _ribbon.SelectedTabItem = TabArtikelNeu
        TabArtikel.IsEnabled = True
        TabControl1.SelectedItem = TabItem3
        BackStageMenu.IsEnabled = False
        tb_artnr.IsEnabled = False
        '### Die Artikeldaten eintragen ###'
        Dim article As ArticlePreviewModel = ListView2.SelectedItem
        ArtikelDatenWeitergeben(loader.GetArticle(article.ArticleID, CurrentUser))
    End Sub

    Private Sub buttonArticleStats_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles buttonArticleStats.Click
        StatsContextGroup.Visibility = Windows.Visibility.Visible
        statscomingfrom = _ribbon.SelectedTabItem
        _ribbon.SelectedTabItem = TabStats

        calendarArticleStatsStart.SelectedDate = New Date(Date.Today.Year, 1, 1)
        calendarArticleStatsStart.DisplayDate = New Date(Date.Today.Year, 1, 1)
        calendarArticleStatsEnd.SelectedDate = New Date(Date.Today.Year, 12, 31)
        calendarArticleStatsEnd.DisplayDate = New Date(Date.Today.Year, 12, 31)
    End Sub

    Private Sub calendarArticleStatsStart_SelectedDatesChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles calendarArticleStatsStart.SelectedDatesChanged
        Try
            articlestats.GetMostBoughtArticlesAsync(calendarArticleStatsStart.SelectedDate, calendarArticleStatsEnd.SelectedDate)
        Catch ex As Exception : End Try
    End Sub

    Private Sub calendarArticleStatsEnd_SelectedDatesChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles calendarArticleStatsEnd.SelectedDatesChanged
        Try
            articlestats.GetMostBoughtArticlesAsync(calendarArticleStatsStart.SelectedDate, calendarArticleStatsEnd.SelectedDate)
        Catch ex As Exception : End Try
    End Sub

    Private Sub GetMostBoughtArticlesCompleted(result As Collection(Of ArticleAmountModel))
        LVArticlesSalesList.ItemsSource = result
    End Sub

#Region "Articlelist"
    Private Sub buttonArtikellistePDF_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles buttonArtikellistePDF.Click
        Dim dlg As New System.Windows.Forms.SaveFileDialog()
        dlg.Title = "Artikelliste speichern"
        dlg.DefaultExt = ".pdf" ' Default file extension
        dlg.Filter = "PDF-Dokument |*.pdf" ' Filter files by extension
        dlg.FileName = "Sicherung " + Datum.Today
        If dlg.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Dim content As New Collection(Of String)
            For Each r In articlevm.DisplayedArticles
                content.Add(r.ArticleID)
                content.Add(r.ArticleDescription)
                content.Add(r.ArticlePrice.ToString)
                content.Add(r.ArticleUnit)
            Next

            Dim captions As New Collection(Of String)
            captions.Add(GetUIString("articlenumber"))
            captions.Add(GetUIString("articledescription"))
            captions.Add(GetUIString("price"))
            captions.Add(GetUIString("unit"))

            Dim widths As New Collection(Of Single)
            widths.Add(2S)
            widths.Add(4S)
            widths.Add(1S)
            widths.Add(1S)
            Dim export As New TablePDFExport()
            export.OpenFileAfterCreation = True
            export.TableStyle = tablestyle
            export.FilePath = dlg.FileName
            export.CreateTable(GetUIString("articlelist"), captions, content, widths)
        End If
    End Sub

    Private Sub buttonArtikellisteDrucken_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles buttonArtikellisteDrucken.Click
        Dim content As New Collection(Of String)
        For Each r In articlevm.DisplayedArticles
            content.Add(r.ArticleID)
            content.Add(r.ArticleDescription)
            content.Add(r.ArticlePrice.ToString)
            content.Add(r.ArticleUnit)
        Next

        Dim captions As New Collection(Of String)
        captions.Add(GetUIString("articlenumber"))
        captions.Add(GetUIString("articledescription"))
        captions.Add(GetUIString("price"))
        captions.Add(GetUIString("unit"))

        Dim widths As New Collection(Of Single)
        widths.Add(2S)
        widths.Add(4S)
        widths.Add(1S)
        widths.Add(1S)
        Dim export As New TablePDFExport()
        export.OpenFileAfterCreation = True
        export.TableStyle = tablestyle
        export.CreateTable(GetUIString("articlelist"), captions, content, widths)
    End Sub
#End Region
#End Region

#Region "ContextTab Artikel"
    ''' <summary>
    ''' Speichern und Zurück
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub buttonArtikelSpeichern_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonArtikelSpeichern.Click
        If SaveArticle() = True Then
            TabArtikel.IsEnabled = True
            _ribbon.SelectedTabItem = TabArtikel
            ArtikelerstellenbearbeitenBoxenLeeren()
            ArtikelContextGroup.Visibility = Windows.Visibility.Collapsed
            BackStageMenu.IsEnabled = True
        End If
    End Sub

    ''' <summary>
    ''' Artikel zwischenspeichern
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub buttonArtikelzwischenspeichern_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonArtikelzwischenspeichern.Click
        SaveArticle()
    End Sub

    ''' <summary>
    ''' Artikel aus Vorlage erstellen
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub buttonArtikelVorlage_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonArtikelVorlage.Click
        TabControl1.SelectedItem = TabItem2
    End Sub

    ''' <summary>
    ''' Artikel erstellen abbrechen
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub buttonArtikelAbbrechen_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonArtikelAbbrechen.Click
        'Boxen leeren
        ArtikelerstellenbearbeitenBoxenLeeren()
        ArtikeldatenTabItem.DataContext = Nothing
        TabArtikel.IsEnabled = True
        _ribbon.SelectedTabItem = TabArtikel
        ArtikelContextGroup.Visibility = Windows.Visibility.Collapsed
        BackStageMenu.IsEnabled = True
        ArtikeldatenTabItem.DataContext = Nothing
    End Sub

    Private Sub ArtikelerstellenbearbeitenBoxenLeeren()
        tb_artbez.Text = ""
        tb_arttxt.Text = ""
        tb_artnr.Text = ""
        tb_preis_1.Text = ""
        tb_preis_2.Text = ""
        tb_preis_3.Text = ""
        cb_einheit.SelectedIndex = -1
        ComboBox9.SelectedIndex = -1
    End Sub

    Private Function SaveArticle() As Boolean
        If cb_einheit.SelectedIndex = -1 OrElse ComboBox9.SelectedIndex = -1 Then
            If TaskDialog.IsPlatformSupported Then
                Dim td As New TaskDialog()
                td.Cancelable = True
                td.Icon = TaskDialogStandardIcon.Error
                td.Caption = "Eigenschaften festlegen"
                td.InstructionText = "Erforderliche Eigenschaften festlegen"
                td.Text = "Es wurden noch nicht alle erforderlichen Eigenschaften festgelegt!"
                Dim subline As String = ""
                If cb_einheit.SelectedIndex = -1 Then
                    subline = "Artikeleinheit "
                End If
                If cb_einheit.SelectedIndex = -1 Then
                    If String.IsNullOrEmpty(subline) Then
                        subline = "Es fehlt eine Steuerklasse"
                    Else
                        subline += "und Steuerklasse"
                        subline = "Es fehlt die " + subline
                    End If
                Else
                    subline = "Es fehlt die " + subline
                End If
                Dim okbutton As New TaskDialogCommandLink("sendButton", "Ok" + Constants.vbLf + subline)
                td.Controls.Add(okbutton)
                td.Show()
                Return False
            Else
                PSTaskDialog.cTaskDialog.ForceEmulationMode = True
                PSTaskDialog.cTaskDialog.EmulatedFormWidth = 450
                PSTaskDialog.cTaskDialog.MessageBox("Eigenschaften festlegen", "Erforderliche Eigenschaften festlegen", "Es wurden noch nicht alle erforderlichen Eigenschaften festgelegt!", PSTaskDialog.eTaskDialogButtons.OK, PSTaskDialog.eSysIcons.Error)
                Return False
            End If
            Exit Function
        End If

        FocusTBParentForMVVM(tb_artbez)

        Dim art As Article = ArtikeldatenTabItem.DataContext
        art.ArticleUnit = cb_einheit.SelectedItem
        art.TaxClass = ComboBox9.SelectedItem
        art.ArticlePrice1.IsGross = CBool(ComboBox3.SelectedIndex)
        art.ArticlePrice2.IsGross = CBool(ComboBox4.SelectedIndex)
        art.ArticlePrice3.IsGross = CBool(ComboBox5.SelectedIndex)
        If TreeView3.SelectedItem IsNot Nothing Then
            If TreeView3.SelectedItem.Name = "Alle Kategorien" Then
                art.ArticleCategory = ""
            Else
                Dim tmp As String = ""
                Dim sitem = TreeView3.SelectedItem
                tmp = "/" + sitem.Name
                While True
                    Try
                        sitem = sitem.Parent
                        tmp = "/" + sitem.Name + tmp
                    Catch ex As Exception
                        Exit While
                    End Try
                End While
                art.ArticleCategory = tmp
            End If
        Else
            art.ArticleCategory = ""
        End If

        articlevm.SaveArticle(art)
        Return True
    End Function

    Private Sub tb_artnr_TextChanged(sender As System.Object, e As System.Windows.Controls.TextChangedEventArgs) Handles tb_artnr.TextChanged
        If Article.Exists(tb_artnr.Text, loader, CurrentUser) Then
            tb_artnr.Foreground = Brushes.Red
        Else
            tb_artnr.Foreground = tb_artbez.Foreground
        End If
    End Sub

#Region "AutoFocus"
    Private Sub tb_preis_1_GotFocus(sender As Object, e As RoutedEventArgs) Handles tb_preis_1.GotFocus
        System.Threading.Tasks.Task.Factory.StartNew(Sub()
                                                         System.Threading.Thread.Sleep(150)
                                                         Dispatcher.BeginInvoke(Sub()
                                                                                    Try
                                                                                        Dim txt As String = tb_preis_1.Text
                                                                                        txt = txt.Replace(CType(tb_preis_1.DataContext, Article).ArticlePrice1.GetCurrencySymbol, "").Trim
                                                                                        tb_preis_1.Select(tb_preis_1.Text.IndexOf(txt), txt.Length)
                                                                                    Catch ex As Exception : End Try
                                                                                End Sub)
                                                     End Sub)
    End Sub

    Private Sub tb_preis_2_GotFocus(sender As Object, e As RoutedEventArgs) Handles tb_preis_2.GotFocus
        System.Threading.Tasks.Task.Factory.StartNew(Sub()
                                                         System.Threading.Thread.Sleep(150)
                                                         Dispatcher.BeginInvoke(Sub()
                                                                                    Try
                                                                                        Dim txt As String = tb_preis_2.Text
                                                                                        txt = txt.Replace(CType(tb_preis_2.DataContext, Article).ArticlePrice2.GetCurrencySymbol, "").Trim
                                                                                        tb_preis_2.Select(tb_preis_2.Text.IndexOf(txt), txt.Length)
                                                                                    Catch ex As Exception : End Try
                                                                                End Sub)
                                                     End Sub)
    End Sub

    Private Sub tb_preis_3_GotFocus(sender As Object, e As RoutedEventArgs) Handles tb_preis_3.GotFocus
        System.Threading.Tasks.Task.Factory.StartNew(Sub()
                                                         System.Threading.Thread.Sleep(150)
                                                         Dispatcher.BeginInvoke(Sub()
                                                                                    Try
                                                                                        Dim txt As String = tb_preis_3.Text
                                                                                        txt = txt.Replace(CType(tb_preis_3.DataContext, Article).ArticlePrice3.GetCurrencySymbol, "").Trim
                                                                                        tb_preis_3.Select(tb_preis_3.Text.IndexOf(txt), txt.Length)
                                                                                    Catch ex As Exception : End Try
                                                                                End Sub)
                                                     End Sub)
    End Sub
#End Region
#End Region

#Region "Tab Kunde"
    Private chooseCustomerforAuftrag As Boolean = False
    Private Sub ListViewKunden_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles ListViewKunden.SelectionChanged
        If ListViewKunden.SelectedItems.Count = 1 Then
            buttonKundeBearbeiten.IsEnabled = True
            buttonKundeloeschen.IsEnabled = True
        Else
            buttonKundeBearbeiten.IsEnabled = False
            buttonKundeloeschen.IsEnabled = False
        End If
    End Sub

    Private Sub ListViewKunden_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles ListViewKunden.MouseDoubleClick
        If ListViewKunden.SelectedItems.Count = 1 Then
            If chooseCustomerforAuftrag Then
                Dim c As CustomerPreviewModel = ListViewKunden.SelectedItem
                SendRequestedCustomer(c.CustomerID)
                chooseCustomerforAuftrag = False
            Else
                KundendatenBearbeiten()
            End If
        End If
    End Sub

    Private Sub buttonNeuerKunde_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonNeuerKunde.Click
        Try
            KundeContextGroup.Header = "Kunde anlegen"
            KundeContextGroup.Visibility = Windows.Visibility.Visible
            _ribbon.SelectedTabItem = TabKundeNeu
            TabKunde.IsEnabled = False
            KundeContextGroup.Visibility = Windows.Visibility.Visible
            BackStageMenu.IsEnabled = False
            TabControl1.SelectedItem = TabItem6
            CustomerDataPreview.Visibility = Windows.Visibility.Collapsed
            CustomerStatsTabItem.Visibility = Windows.Visibility.Collapsed
            RibbonGroupBoxCustomerStats.Visibility = Windows.Visibility.Collapsed
            KundeTabControl.DataContext = New Customer(True, CustomerViewModel.AllCustomers)
            customereditcontrol.DataContext = KundeTabControl.DataContext
            KundeTabControl.SelectedIndex = 2
        Catch ex As Exception
            log.AddEntry(ex.ToString)
        End Try
    End Sub

    Private Sub KundenSuche()
        If isloading = False Then
            customervm.SearchPattern = SearchTextBox2.Text.ToLower
        End If
    End Sub

    Private Sub SearchTextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles SearchTextBox2.TextChanged, RadioButton3.Checked
        KundenSuche()
    End Sub

    Private Sub RadioButton2_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles RadioButton2.Checked
        KundenSuche()
    End Sub

    Private Sub TreeView2_SelectedItemChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedPropertyChangedEventArgs(Of System.Object)) Handles TreeView2.SelectedItemChanged
        Dim item As TreeViewItem = TreeView2.SelectedItem
        Dim b As String = item.Header

        If b.Contains("Alle Kunden") Then
            customervm.XPathCategory = ""
        ElseIf b.Contains("Sonstig") Then

        Else
            b = Mid(b, 1, 1)
            customervm.XPathCategory = b
        End If
    End Sub

    Private Sub buttonKundeBearbeiten_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonKundeBearbeiten.Click
        KundendatenBearbeiten()
    End Sub

    Private Sub KundendatenBearbeiten()
        Try
            KundeContextGroup.Header = "Kunde bearbeiten"
            _ribbon.SelectedTabItem = TabKundeNeu
            TabKunde.IsEnabled = False
            KundeContextGroup.Visibility = Windows.Visibility.Visible
            CustomerDataPreview.Visibility = Windows.Visibility.Visible
            BackStageMenu.IsEnabled = False
            Dim c As CustomerPreviewModel = ListViewKunden.SelectedItem
            TabControl1.SelectedItem = TabItem6
            KundeTabControl.DataContext = loader.GetCustomer(c.CustomerID, CurrentUser)
            customereditcontrol.DataContext = KundeTabControl.DataContext
            '### Statistik ###'
            CustomerStatsTabItem.Visibility = Windows.Visibility.Visible
            RibbonGroupBoxCustomerStats.Visibility = Windows.Visibility.Visible

            KundeTabControl.SelectedIndex = 1
        Catch ex As Exception
            log.AddEntry(ex.ToString)
        End Try
    End Sub

    Private Sub buttonKundeloeschen_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonKundeloeschen.Click
        KundeDeleteRequest(ListViewKunden.SelectedItem)
    End Sub

    Private Sub KundeDeleteRequest(customer As CustomerPreviewModel)
        Dim result As Forms.DialogResult
        Dim b As Boolean = ToggleButton3.IsChecked
        If b = True Then
            If TaskDialog.IsPlatformSupported Then
                Dim td As New TaskDialog()
                td.Cancelable = True
                td.Icon = TaskDialogStandardIcon.Shield
                td.Caption = "Kunde löschen?"
                td.InstructionText = "Wollen sie diesen Kunden wirklich löschen?"
                td.Text = "Aufträge, die diesem Kunden zugeordnet sind, können möglicherweise nicht mehr korrekt geöffnet bzw. gedruckt werden."
                td.StandardButtons = TaskDialogStandardButtons.Yes Or TaskDialogStandardButtons.No

                td.FooterCheckBoxChecked = b
                td.FooterCheckBoxText = "Meldung jedes mal zeigen."
                If td.Show() = TaskDialogResult.Yes Then
                    result = Forms.DialogResult.Yes
                Else
                    result = Forms.DialogResult.No
                End If
                ToggleButton3.IsChecked = td.FooterCheckBoxChecked
            Else
                PSTaskDialog.cTaskDialog.ForceEmulationMode = True
                PSTaskDialog.cTaskDialog.EmulatedFormWidth = 450
                result = PSTaskDialog.cTaskDialog.MessageBox("Kunde löschen?", "Wollen sie diesen Kunden wirklich löschen?", "Aufträge, die diesem Kunden zugeordnet sind, können möglicherweise nicht mehr korrekt geöffnet bzw. gedruckt werden.", PSTaskDialog.eTaskDialogButtons.YesNo, PSTaskDialog.eSysIcons.Warning)
            End If
        Else
            result = Forms.DialogResult.Yes
        End If

        If result = Forms.DialogResult.Yes Then
            Try
                loader.DeleteCustomer(customer.CustomerID, CurrentUser)
                customervm.Refresh()
            Catch ex As Exception
                log.AddEntry(ex.ToString)
            End Try
        End If
    End Sub

    Private Sub buttonKundenlistePDF_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles buttonKundenlistePDF.Click
        Dim dlg As New System.Windows.Forms.SaveFileDialog()
        dlg.Title = "Kundenliste speichern"
        dlg.DefaultExt = ".pdf" ' Default file extension
        dlg.Filter = "PDF-Dokument |*.pdf" ' Filter files by extension
        dlg.FileName = "Sicherung " + Datum.Today
        If dlg.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Dim content As New Collection(Of String)
            For Each c In customervm.DisplayedCustomers
                content.Add(c.CustomerID)
                content.Add(c.DisplayedName)
                content.Add(c.Address.ToString)
            Next

            Dim captions As New Collection(Of String)
            captions.Add(GetUIString("customerno"))
            captions.Add(GetUIString("customername"))
            captions.Add(GetUIString("address"))

            Dim widths As New Collection(Of Single)
            widths.Add(1S)
            widths.Add(1S)
            widths.Add(3S)

            Dim export As New TablePDFExport()
            export.OpenFileAfterCreation = True
            export.TableStyle = tablestyle
            export.FilePath = dlg.FileName
            Try
                export.CreateTable(GetUIString("customerreport"), captions, content, widths)
            Catch ex As Exception
                log.AddEntry(ex.ToString)
            End Try
        End If
    End Sub

    Private Sub buttonKundenlisteDrucken_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles buttonKundenlisteDrucken.Click
        Dim content As New Collection(Of String)
        For Each c In customervm.DisplayedCustomers
            content.Add(c.CustomerID)
            content.Add(c.DisplayedName)
            content.Add(c.Address.ToString)
        Next

        Dim captions As New Collection(Of String)
        captions.Add(GetUIString("customerno"))
        captions.Add(GetUIString("customername"))
        captions.Add(GetUIString("address"))

        Dim widths As New Collection(Of Single)
        widths.Add(1S)
        widths.Add(1S)
        widths.Add(3S)

        Dim export As New TablePDFExport()
        export.OpenFileAfterCreation = True
        export.TableStyle = tablestyle
        Try
            export.CreateTable(GetUIString("customerreport"), captions, content, widths)
        Catch ex As Exception
            log.AddEntry(ex.ToString)
        End Try
    End Sub

#Region "CustomerSalesList"

    Private Sub buttonCustomerStats_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles buttonCustomerStats.Click
        StatsContextGroup.Visibility = Windows.Visibility.Visible
        statscomingfrom = _ribbon.SelectedTabItem
        _ribbon.SelectedTabItem = TabStats
        calendarCustomerSalesStart.SelectedDate = New Date(Date.Today.Year, 1, 1)
        calendarCustomerSalesStart.DisplayDate = New Date(Date.Today.Year, 1, 1)
        calendarCustomerSalesEnd.SelectedDate = New Date(Date.Today.Year, 12, 31)
        calendarCustomerSalesEnd.DisplayDate = New Date(Date.Today.Year, 12, 31)
    End Sub
#End Region
#End Region

#Region "ContextTab Kunde"
    Private Sub buttonKundezwischenspeichern_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonKundezwischenspeichern.Click
        Try
            customereditcontrol.Save(CustomerViewModel)
        Catch ex As Exception
            log.AddEntry(ex.ToString)
        End Try
    End Sub

    Private Sub buttonKundeSpeichern_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonKundeSpeichern.Click
        Try
            customereditcontrol.Save(CustomerViewModel)
            TabKunde.IsEnabled = True
            _ribbon.SelectedTabItem = TabKunde
            KundeContextGroup.Visibility = Windows.Visibility.Collapsed
            GridKundeContainer.DataContext = Nothing
            KundeTabControl.DataContext = Nothing
            BackStageMenu.IsEnabled = True

            KundeTabControl.SelectedIndex = 1
        Catch ex As Exception
            log.AddEntry(ex.ToString)
        End Try
    End Sub

    Private Sub buttonKundenAbbrechen_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonKundenAbbrechen.Click
        Try
            TabKunde.IsEnabled = True
            _ribbon.SelectedTabItem = TabKunde
            KundeContextGroup.Visibility = Windows.Visibility.Collapsed
            BackStageMenu.IsEnabled = True
            GridKundeContainer.DataContext = Nothing
            KundeTabControl.DataContext = Nothing
            KundeTabControl.SelectedIndex = 1
        Catch ex As Exception
            log.AddEntry(ex.ToString)
        End Try
    End Sub

#Region "Umsatzübersicht"
    Private calendar As New Windows.Controls.Calendar
    Private state As CalendarState = CalendarState.Uninitialized
    Private customerStatsStartDate, customerStatsEndDate As Date

    ''' <summary>
    ''' Statistik Startdatum
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub buttonKundenStatsStartDate_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles buttonKundenStatsStartDate.Click
        Try
            If state = CalendarState.Start Then
                GridMain.Children.Remove(calendar)
                state = CalendarState.Uninitialized
            Else
                calendar.SelectedDate = customerStatsStartDate
                state = CalendarState.Start
                If GridMain.Children.Contains(calendar) Then
                    GridMain.Children.Remove(calendar)
                End If
                calendar.Visibility = Windows.Visibility.Visible
                GridMain.Children.Add(calendar)
                ' Return the offset vector for the TextBlock object.
                Dim vector As Windows.Vector = VisualTreeHelper.GetOffset(buttonKundenStatsStartDate)

                ' Convert the vector to a point value.
                Dim p As New Windows.Point(vector.X, vector.Y)
                p.X += buttonKundenStatsStartDate.ActualWidth / 2
                'p.X -= 180 / 2
                calendar.Margin = New Thickness(p.X, 0, 0, 0)
                calendar.HorizontalAlignment = Windows.HorizontalAlignment.Left
            End If
        Catch ex As Exception
            log.AddEntry(ex.ToString)
        End Try
    End Sub

    ''' <summary>
    ''' Statistik Enddatum
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub buttonKundenStatsEndDate_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles buttonKundenStatsEndDate.Click
        Try
            If state = CalendarState.Ende Then
                GridMain.Children.Remove(calendar)
                state = CalendarState.Uninitialized
            Else
                calendar.SelectedDate = customerStatsEndDate
                state = CalendarState.Ende
                If GridMain.Children.Contains(calendar) Then
                    GridMain.Children.Remove(calendar)
                End If
                calendar.Visibility = Windows.Visibility.Visible
                GridMain.Children.Add(calendar)
                ' Return the offset vector for the TextBlock object.
                Dim vector As Windows.Vector = VisualTreeHelper.GetOffset(buttonKundenStatsEndDate)

                ' Convert the vector to a point value.
                Dim p As New Windows.Point(vector.X, vector.Y)
                p.X += buttonKundenStatsEndDate.ActualWidth / 2
                'p.X -= 180 / 2
                calendar.Margin = New Thickness(p.X, 0, 0, 0)
                calendar.HorizontalAlignment = Windows.HorizontalAlignment.Left
            End If
        Catch ex As Exception
            log.AddEntry(ex.ToString)
        End Try
    End Sub

    Enum CalendarState
        Start = 0
        Ende = 1
        Uninitialized = 2
    End Enum

    Private Sub Calendar1_SelectedDatesChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) 'Handles calendar.SelectedDatesChanged
        Select Case state
            Case CalendarState.Start
                customerStatsStartDate = calendar.SelectedDate
            Case CalendarState.Ende
                customerStatsEndDate = calendar.SelectedDate
        End Select
        Try
            customerstatistic.GetMonthlySalesAsync(DirectCast(customereditcontrol.DataContext, Customer).CustomerID, customerStatsStartDate, customerStatsEndDate)
            customerstatistic.GetMostBoughtArticlesAsync(DirectCast(customereditcontrol.DataContext, Customer).CustomerID, customerStatsStartDate, customerStatsEndDate)
            Label16.Content = New Datum(customerStatsStartDate).ToString + " bis " + New Datum(customerStatsEndDate).ToString
        Catch ex As Exception
            log.AddEntry(ex.ToString)
        End Try
    End Sub

    Private Sub ListView4_MouseDoubleClick(sender As System.Object, e As System.Windows.Input.MouseButtonEventArgs) Handles ListView4.MouseDoubleClick
        If ListView4.SelectedItems.Count = 1 Then
            Dim o As OrderPreviewModel = ListView4.SelectedItem
            LoadOrder(loader.GetOrder(o.OrderID, o.OrderTyp, CurrentUser))
        End If
    End Sub

    Private Sub chart_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles chart.Loaded
        Try
            If Not isloading Then
                Dim k1 As Customer = GridKundeContainer.DataContext
                Dim w As Double = chart.ActualWidth
                If w > 0 Then
                    Dim today As Date = Date.Today
                    Dim abzug As Integer = (-1) * (w / 140)
                    customerstatistic.GetMonthlySalesAsync(k1.CustomerID, today.AddMonths(abzug), today)
                    Dim start As New Datum(today.AddMonths(abzug))
                    start.Tag = 1
                    Label16.Content = start.ToString + " bis " + New Datum(today).ToString

                    customerStatsStartDate = New Date(start.Jahr, start.Monat, start.Tag)
                    customerStatsEndDate = today
                End If
            End If
        Catch ex As Exception
            log.AddEntry(ex.ToString)
        End Try
    End Sub

    Private Sub CustomerMonthlySalesCompleted(result As Collection(Of DateValueModel))
        chart.DataContext = result
    End Sub

    Private Sub KundeTabControl_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles KundeTabControl.SelectionChanged
        If KundeTabControl.SelectedIndex = 2 AndAlso isloading = False Then
            Try
                Dim k1 As Customer = DirectCast(GridKundeContainer.DataContext, Customer)
                customerstatistic.GetMostBoughtArticlesAsync(k1.CustomerID, customerStatsStartDate, customerStatsEndDate)
            Catch ex As Exception
                log.AddEntry(ex.ToString)
            End Try
        End If
    End Sub

    Private Sub MostBoughtArticlesofCustomerCompleted(result As Collection(Of ArticleAmountModel))
        LVMBACustomer.DataContext = result
        MBACchart.DataContext = result
    End Sub
#End Region
#End Region

#Region "Tab Settings"
#Region "Artikeleinheiten"
    ''' <summary>
    ''' Neue Einheit speichern
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button2.Click
        If Not String.IsNullOrEmpty(TextBox23.Text) Then
            Dim unit As New Unit(TextBox23.Text, TextBox24.Text, loader) With {.UnitFormat = tb_unitformat.Text}
            unit.Save()
            ListViewArticleUnits.SelectedIndex = -1
            If SettingsViewModel.ArticleUnits.Contains(unit) Then
                Dim index = SettingsViewModel.ArticleUnits.IndexOf(unit)
                SettingsViewModel.ArticleUnits.Remove(unit)
                SettingsViewModel.ArticleUnits.Insert(index, unit)
            Else
                SettingsViewModel.ArticleUnits.Add(unit)
            End If
        End If
    End Sub
#End Region
#Region "Steuerklassen"
    ''' <summary>
    ''' Steuerklasse speichern
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button3.Click
        If Not String.IsNullOrEmpty(TextBox25.Text) Then
            Dim tax As New TaxClass(TextBox25.Text, TextBox26.Text, loader)
            tax.Save()
            If SettingsViewModel.TaxClasses.Contains(tax) Then
                Dim index = SettingsViewModel.TaxClasses.IndexOf(tax)
                SettingsViewModel.TaxClasses.Remove(tax)
                SettingsViewModel.TaxClasses.Insert(index, tax)
            Else
                SettingsViewModel.TaxClasses.Add(tax)
            End If
        End If
    End Sub

    Private Sub RadioButton4_Checked(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles RadioButton4.Checked
        loader.TaxDescription = "mwst"
    End Sub

    Private Sub RadioButton5_Checked(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles RadioButton5.Checked
        loader.TaxDescription = "ust"
    End Sub

#End Region
#Region "Zahlungsart"
    ''' <summary>
    ''' Neue Zahlungsart
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button12_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button12.Click
        If Not String.IsNullOrEmpty(TextBox123.Text) Then
            Dim pm As PaymentMethode
            Try
                pm = New PaymentMethode(TextBox123.Text, TextBox124.Text, CDec(TextBox125.Text.Replace("%", "").Replace(" ", "")) / 100)
                PaymentMethode.AddPaymentMethode(pm, loader)
            Catch ex As Exception
                pm = New PaymentMethode(TextBox123.Text, TextBox124.Text, 0.0)
                PaymentMethode.AddPaymentMethode(pm, loader)
            End Try
            ListViewPaymentMethodes.SelectedIndex = -1
            If SettingsViewModel.PaymentMethodes.Contains(pm) Then
                Dim index = SettingsViewModel.PaymentMethodes.IndexOf(pm)
                SettingsViewModel.PaymentMethodes.Remove(pm)
                SettingsViewModel.PaymentMethodes.Insert(index, pm)
            Else
                SettingsViewModel.PaymentMethodes.Add(pm)
            End If
        End If
    End Sub

    ''' <summary>
    ''' Platzhalter Skontobetrag
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button21_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button21.Click
        Dim cindex As Integer = TextBox124.CaretIndex
        If ListViewPaymentMethodes.SelectedItem Is Nothing Then
            TextBox124.Text = TextBox124.Text.Insert(TextBox124.CaretIndex, "{0}")
            TextBox124.CaretIndex = cindex + 3
        Else
            FocusTBParentForMVVM(TextBox124)
            Dim payment As PaymentMethode = ListViewPaymentMethodes.SelectedItem
            payment.Text = payment.Text.Insert(cindex, "{0}")
            TextBox124.Focus()
            TextBox124.CaretIndex = cindex + 3
        End If
    End Sub

    ''' <summary>
    ''' Platzhalter Endbetrag inkl. Skonto
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button22_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button22.Click
        Dim cindex As Integer = TextBox124.CaretIndex
        If ListViewPaymentMethodes.SelectedItem Is Nothing Then
            TextBox124.Text = TextBox124.Text.Insert(TextBox124.CaretIndex, "{1}")
            TextBox124.CaretIndex = cindex + 3
        Else
            FocusTBParentForMVVM(TextBox124)
            Dim payment As PaymentMethode = ListViewPaymentMethodes.SelectedItem
            payment.Text = payment.Text.Insert(cindex, "{1}")
            TextBox124.Focus()
            TextBox124.CaretIndex = cindex + 3
        End If
    End Sub
#End Region
#Region "Auftragstext"
    ''' <summary>
    ''' Auftragstext Vorlage Speichern
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Button13_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button13.Click
        If Not String.IsNullOrEmpty(TextBox38.Text) Then
            FocusTBParentForMVVM(TextBox38)
            Dim ordertext = New nHibernate.Models.OrderTextModel With {.Name = TextBox38.Text, .Text = TextBox39.Text}
            loader.SaveOrUpdateOrderText(ordertext)
            ListViewOrderTexts.SelectedIndex = -1
            If SettingsViewModel.OrderTexts.Contains(ordertext) Then
                Dim index = SettingsViewModel.OrderTexts.IndexOf(ordertext)
                SettingsViewModel.OrderTexts.Remove(ordertext)
                SettingsViewModel.OrderTexts.Insert(index, ordertext)
            Else
                SettingsViewModel.OrderTexts.Add(ordertext)
            End If
        End If
    End Sub
#End Region

    Private Sub buttonSettings_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonSettings.Click
        TabControl1.SelectedItem = TabItem7
    End Sub

    Private Sub buttonImportieren_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles buttonImportieren.Click
        TabControl1.SelectedItem = TabItem8
    End Sub

    Private Sub SettingsTabControl_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles SettingsTabControl.SelectionChanged
        If SettingsTabControl.SelectedItem IsNot Nothing Then
            Dim cur As TabItem = SettingsTabControl.SelectedItem
            If cur.Header = SettingsLayout.Header Then
                SettingsLayoutSave.Visibility = Windows.Visibility.Visible
                Exit Sub
            Else
                SettingsLayoutSave.Visibility = Windows.Visibility.Collapsed
            End If
        Else
            SettingsLayoutSave.Visibility = Windows.Visibility.Collapsed
        End If
    End Sub


#Region "Warnings"
    'Order
    Private Sub ToggleButton1_Checked(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ToggleButton1.Checked
        loader.SetSettingByKey("AuftragDelete", True)
    End Sub
    Private Sub ToggleButton1_Unchecked(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ToggleButton1.Unchecked
        loader.SetSettingByKey("AuftragDelete", False)
    End Sub

    'Article
    Private Sub ToggleButton2_Checked(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ToggleButton2.Checked
        loader.SetSettingByKey("ArticleDelete", True)
    End Sub
    Private Sub ToggleButton2_Unchecked(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ToggleButton2.Unchecked
        loader.SetSettingByKey("ArticleDelete", False)
    End Sub

    'Customer
    Private Sub ToggleButton3_Checked(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ToggleButton3.Checked
        loader.SetSettingByKey("CustomerDelete", True)
    End Sub
    Private Sub ToggleButton3_Unchecked(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ToggleButton3.Unchecked
        loader.SetSettingByKey("CustomerDelete", False)
    End Sub

    'AutoBackup
    Private Sub ToggleButton4_Checked(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ToggleButton4.Checked
        If isloading = False Then
            loader.SetSettingByKey("AutoBackupPathEnabled", True)
        End If
    End Sub
    Private Sub ToggleButton4_Unchecked(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ToggleButton4.Unchecked
        If isloading = False Then
            loader.SetSettingByKey("AutoBackupPathEnabled", False)
        End If
    End Sub
    Private Sub TBBackupPath_TextChanged(sender As System.Object, e As System.Windows.Controls.TextChangedEventArgs) Handles TBBackupPath.TextChanged
        If isloading = False Then
            loader.SetSettingByKey("AutoBackupPath", TBBackupPath.Text)
        End If
    End Sub
    Private Sub TBBackupPath_MouseDoubleClick(sender As System.Object, e As System.Windows.Input.MouseButtonEventArgs) Handles TBBackupPath.MouseDoubleClick
        Dim dlg As New System.Windows.Forms.FolderBrowserDialog()
        dlg.ShowNewFolderButton = True
        dlg.Description = "Speicherort für automatische Backups"
        If dlg.ShowDialog = Forms.DialogResult.OK Then
            TBBackupPath.Text = dlg.SelectedPath
        End If
    End Sub
#End Region
#End Region

#Region "Anwendung runterfahren"
    Private Sub RibbonWindow_Closing(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        'ToDo: Speichern von Einstellungen
        'Fensterposition, -größe und -status

        '### Strange Behaviour: the Closing and Closed are called two times!!
        If closechecker Then
            closechecker = False
            exitevent = e
            ClosingRoutines()
        End If
    End Sub
    Private exitevent As System.ComponentModel.CancelEventArgs
    Private Sub ClosingRoutines()
        addinmanager.SaveAddinList()
        If AuftragControlHolder.Count > 0 Then
            If TaskDialog.IsPlatformSupported Then
                Dim td As New TaskDialog()
                td.Cancelable = False
                td.Icon = TaskDialogStandardIcon.Information
                td.Caption = "Aufträge merken"
                td.InstructionText = "Aufträge beim nächsten Start anzeigen?"
                td.Text = "Sie haben noch einen oder mehrere Aufträge geöffnet. Wählen Sie eine der unteren Aktionen:"

                Dim save As New TaskDialogCommandLink("save", "Aufträge speichern" + Constants.vbLf + "Die Aufträge werden beim nächsten Start nicht geladen.")
                AddHandler save.Click, AddressOf save_Click
                Dim notsave As New TaskDialogCommandLink("notsave", "Aufträge verwerfen" + Constants.vbLf + "Nicht gespeicherte Änderungen gehen verloren!")
                AddHandler notsave.Click, AddressOf notsave_Click
                Dim abort As New TaskDialogCommandLink("abort", "Abbrechen" + Constants.vbLf + "Das Programm wird nicht geschlossen.")
                AddHandler abort.Click, AddressOf abort_Click

                If loader.SupportsTemporaryItems Then
                    Dim saveandmark As New TaskDialogCommandLink("saveandmark", "Aufträge speichern und merken" + Constants.vbLf + "Die Aufträge werden beim nächsten Start automatisch geladen.")
                    AddHandler saveandmark.Click, AddressOf saveandmark_Click
                    td.Controls.Add(saveandmark)
                End If
                
                td.Controls.Add(save)
                td.Controls.Add(notsave)
                td.Controls.Add(abort)
                td.Show()
            Else
                PSTaskDialog.cTaskDialog.ForceEmulationMode = True
                PSTaskDialog.cTaskDialog.EmulatedFormWidth = 450
                If loader.SupportsTemporaryItems Then
                    Select Case PSTaskDialog.cTaskDialog.ShowCommandBox("Aufträge merken", "Aufträge beim nächsten Start anzeigen?", "Sie haben noch einen oder mehrere Aufträge geöffnet. Wählen Sie eine der unteren Aktionen:", "Aufträge zwischenspeichern und merken|Aufträge speichern|Aufträge verwerfen|Abbrechen", False)
                        Case 0
                            saveandmark_Click(Nothing, Nothing)
                        Case 1
                            save_Click(Nothing, Nothing)
                        Case 2
                            notsave_Click(Nothing, Nothing)
                        Case 3
                            abort_Click(Nothing, Nothing)
                    End Select
                Else
                    Select Case PSTaskDialog.cTaskDialog.ShowCommandBox("Aufträge merken", "Aufträge beim nächsten Start anzeigen?", "Sie haben noch einen oder mehrere Aufträge geöffnet. Wählen Sie eine der unteren Aktionen:", "Aufträge speichern|Aufträge verwerfen|Abbrechen", False)
                        Case 0
                            save_Click(Nothing, Nothing)
                        Case 1
                            notsave_Click(Nothing, Nothing)
                        Case 2
                            abort_Click(Nothing, Nothing)
                    End Select
                End If
            End If
        End If
        AutomaticBackup()
    End Sub

    Private Sub saveandmark_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim list As New Collection(Of Order)
        For Each kvp As KeyValuePairs In AuftragControlHolder
            Dim c As AuftragControl = kvp.Value
            list.Add(c.CompleteAuftrag)
        Next
        loader.SaveTemps(list, New Collection(Of Customer), New Collection(Of Article), CurrentUser)
        Try
            Dim host As TaskDialogCommandLink = sender
            Dim parent As TaskDialog = host.HostingDialog
            parent.Close()
        Catch ex As Exception : End Try
    End Sub

    Private Sub save_Click(ByVal sender As Object, ByVal e As EventArgs)
        For Each kvp As KeyValuePairs In AuftragControlHolder
            Dim c As AuftragControl = kvp.Value
            ordervm.SaveOrder(c.CompleteAuftrag)
        Next
        Try
            Dim host As TaskDialogCommandLink = sender
            Dim parent As TaskDialog = host.HostingDialog
            parent.Close()
        Catch ex As Exception : End Try
    End Sub

    Private Sub notsave_Click(ByVal sender As Object, ByVal e As EventArgs)
        Try
            Dim host As TaskDialogCommandLink = sender
            Dim parent As TaskDialog = host.HostingDialog
            parent.Close()
        Catch ex As Exception : End Try
    End Sub

    Private Sub abort_Click(ByVal sender As Object, ByVal e As EventArgs)
        Try
            Dim host As TaskDialogCommandLink = sender
            Dim parent As TaskDialog = host.HostingDialog
            parent.Close()
        Catch ex As Exception : End Try
        Try : exitevent.Cancel = True : Catch : End Try
        abortcompanychange = True
        closechecker = True
    End Sub
#End Region

#Region "Importieren"
    WithEvents import As New CSVImport("", loader, Dispatcher, CurrentUser)

    Private Sub TextBox2_MouseDoubleClick(sender As System.Object, e As System.Windows.Input.MouseButtonEventArgs) Handles TextBox2.MouseDoubleClick
        Dim dlg As New System.Windows.Forms.OpenFileDialog
        dlg.Title = "Daten importieren"
        dlg.DefaultExt = ".txt" ' Default file extension
        dlg.Filter = "Textdokument |*.txt" ' Filter files by extension

        ' Process open file dialog box results
        If dlg.ShowDialog() = Forms.DialogResult.OK Then
            import.FilePath = dlg.FileName
        End If
    End Sub

    Private Sub ButtonArticleImport_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonArticleImport.Click
        If String.IsNullOrEmpty(import.FilePath) = False Then
            FocusTBParentForMVVM(UnFocusTB2)
            PRArticleImport.IsActive = True
            ButtonArticleImport.IsEnabled = False
            import.AsyncGetArticles()
        End If
    End Sub

    Private Sub ButtonCustomerImport_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonCustomerImport.Click
        If String.IsNullOrEmpty(import.FilePath) = False Then
            FocusTBParentForMVVM(UnFocusTB2)
            PRCustomerImport.IsActive = True
            ButtonCustomerImport.IsEnabled = False
            import.GetCustomers()
        End If
    End Sub

    Private Sub ButtonOrderImport_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonOrderImport.Click
        If String.IsNullOrEmpty(import.FilePath) = False Then
            FocusTBParentForMVVM(UnFocusTB2)
            PROrderImport.IsActive = True
            ButtonOrderImport.IsEnabled = False
            import.GetAuftraege()
        End If
    End Sub

    Private Sub GetOrdersCompleted(ByVal orders As ObservableCollection(Of Order)) Handles import.GetOrdersCompleted
        Dim t As Task = Task.Factory.StartNew(Sub()
                                                  For Each Order As Order In orders
                                                      ordervm.SaveOrder(Order)
                                                  Next
                                                  Dispatcher.BeginInvoke(Sub()
                                                                             ordervm.Refresh()
                                                                             PROrderImport.IsActive = False
                                                                             ButtonOrderImport.IsEnabled = True
                                                                         End Sub)
                                              End Sub)
    End Sub

    Private Sub GetArticlesCompleted(ByVal art As ObservableCollection(Of Article)) Handles import.GetArticlesCompleted
        Dim t As Task = Task.Factory.StartNew(Sub()
                                                  For Each a As Article In art
                                                      articlevm.SaveArticle(a)
                                                  Next
                                                  Dispatcher.BeginInvoke(Sub()
                                                                             articlevm.Refresh()
                                                                             PRArticleImport.IsActive = False
                                                                             ButtonArticleImport.IsEnabled = True
                                                                         End Sub)
                                              End Sub)
    End Sub

    Private Sub GetCustomersCompleted(ByVal customers As ObservableCollection(Of Customer)) Handles import.GetCustomersCompleted
        Dim t As Task = Task.Factory.StartNew(Sub()
                                                  For Each c As Customer In customers
                                                      customervm.SaveCustomer(c)
                                                  Next
                                                  Dispatcher.BeginInvoke(Sub()
                                                                             customervm.Refresh()
                                                                             PRCustomerImport.IsActive = False
                                                                             ButtonCustomerImport.IsEnabled = True
                                                                         End Sub)
                                              End Sub)
    End Sub
#End Region

#Region "Layout"
    Private Sub ComboBox7_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles ComboBox7.SelectionChanged
        Try
            If isloading OrElse ComboBox7.SelectedItem = Nothing Then
                Exit Sub
            End If
        Catch ex As Exception
            Dim item As ComboBoxItem = ComboBox7.SelectedItem
            LoadLayoutControl(item.Content)
        End Try
    End Sub

    ''' <summary>
    ''' Layoutdaten Speichern
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub buttonLayoutSave_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles buttonLayoutSave.Click
        RaiseEvent SaveLayoutSettings(ComboBox7.Text)
    End Sub



    Public ReadOnly Property LayoutImageControl
        Get
            Return Image1
        End Get
    End Property

    Public Sub SetStandardLayoutImage()
        Image1.Source = New BitmapImage(New Uri("/Biller;component/Biller.ico"))
    End Sub
#End Region

#Region "Artikelkategorien"
    Private Sub Button8_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button8.Click
        Dim cat As New Category
        cat.Name = TextBox35.Text
        If ComboBox8.SelectedIndex >= 0 Then
            cat.DefaultTax = TaxClass.GetByName(ComboBox8.Text, loader)
        End If
        cat.Parent = CType(TreeView1.SelectedItem, UICategory).CurrentCategory
        cat.Parent.Children.Add(cat)
        loader.SetCategory(cat, CurrentUser)
        LoadCategories()
    End Sub

    Private Sub CategoryChanged() Handles editcategory.CategoryChanged
        LoadCategories()
    End Sub

    Private Sub TreeView1_SelectedItemChanged(sender As System.Object, e As System.Windows.RoutedPropertyChangedEventArgs(Of System.Object)) Handles TreeView1.SelectedItemChanged
        Try
            If TreeView1.SelectedItem IsNot Nothing Then
                If TextBox35.Text IsNot "" Then : Button8.IsEnabled = True : End If
            End If
            If TreeView1.SelectedItem IsNot Nothing AndAlso DirectCast(TreeView1.SelectedItem, UICategory).Parent IsNot Nothing Then
                buttonKategorieBearbeiten.IsEnabled = True
            Else
                buttonKategorieBearbeiten.IsEnabled = False
            End If
            If Artikelueberischt.Visibility = Windows.Visibility.Visible Then
                Dim tmp As String = ""
                Dim sitem = TreeView1.SelectedItem
                tmp = "/" + sitem.Name
                While Not IsNothing(sitem.Parent)
                    Try
                        sitem = sitem.Parent
                        tmp = "/" + sitem.Name + tmp
                    Catch ex As Exception
                        Exit While
                    End Try
                End While
                sitem = TreeView1.SelectedItem
                If sitem.Name = "Alle Kategorien" Then
                    articlevm.XPathCategory = ""
                Else
                    articlevm.XPathCategory = tmp
                End If
            End If
        Catch ex As Exception
            log.AddEntry(ex.ToString)
        End Try
    End Sub

    Private Sub buttonKategorieBearbeiten_Click(sender As Object, e As RoutedEventArgs) Handles buttonKategorieBearbeiten.Click
        editcategory.DataContext = Nothing
        editcategory.DataContext = TreeView1.SelectedItem
        GridKategorieBearbeiten.Visibility = Windows.Visibility.Visible
        GridNeueKategorie.Visibility = Windows.Visibility.Collapsed
        Artikelueberischt.Visibility = Windows.Visibility.Collapsed
    End Sub

    Private Sub Button9_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button9.Click
        ComboBox8.SelectedIndex = -1
    End Sub

    Private Sub buttonNeueKategorie_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles buttonNeueKategorie.Click
        GridKategorieBearbeiten.Visibility = Windows.Visibility.Collapsed
        GridNeueKategorie.Visibility = Windows.Visibility.Visible
        Artikelueberischt.Visibility = Windows.Visibility.Collapsed
    End Sub

    Private Sub Button10_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button10.Click
        GridKategorieBearbeiten.Visibility = Windows.Visibility.Collapsed
        GridNeueKategorie.Visibility = Windows.Visibility.Collapsed
        Artikelueberischt.Visibility = Windows.Visibility.Visible
    End Sub

    Private Sub TextBox35_TextChanged(sender As System.Object, e As System.Windows.Controls.TextChangedEventArgs) Handles TextBox35.TextChanged
        If TextBox35.Text = "" OrElse TreeView1.SelectedItem Is Nothing Then
            Button8.IsEnabled = False
        Else
            Button8.IsEnabled = True
        End If
        If loader.CategoryExists(TextBox35.Text, CurrentUser) Then
            lbl_categoryexists.Visibility = Windows.Visibility.Visible
        Else
            lbl_categoryexists.Visibility = Windows.Visibility.Collapsed
        End If
    End Sub

    Private Sub LeaveEditControl() Handles editcategory.LeaveEdit
        GridKategorieBearbeiten.Visibility = Windows.Visibility.Collapsed
        GridNeueKategorie.Visibility = Windows.Visibility.Collapsed
        Artikelueberischt.Visibility = Windows.Visibility.Visible
    End Sub
#End Region

#Region "BackStage"
    Private abortcompanychange As Boolean = False
    Private Sub PerformCompanyChange(ByVal name As String)
        If name <> loader.LastCompany AndAlso isloading = False Then
            If AuftragControlHolder.Count > 0 Then
                If TaskDialog.IsPlatformSupported Then
                    Dim td As New TaskDialog()
                    td.Cancelable = False
                    td.Icon = TaskDialogStandardIcon.Information
                    td.Caption = "Aufträge merken"
                    td.InstructionText = "Aufträge nach dem nächsten Ladevorgang anzeigen?"
                    td.Text = "Sie haben noch einen oder mehrere Aufträge geöffnet. Wählen Sie eine der unteren Aktionen:"

                    Dim saveandmark As New TaskDialogCommandLink("saveandmark", "Aufträge speichern und merken" + Constants.vbLf + "Die Aufträge werden nach dem nächsten Ladevorgang automatisch geladen.")
                    AddHandler saveandmark.Click, AddressOf saveandmark_Click
                    Dim save As New TaskDialogCommandLink("save", "Aufträge speichern" + Constants.vbLf + "Die Aufträge werden nach dem nächsten Ladevorgang nicht geladen.")
                    AddHandler save.Click, AddressOf save_Click
                    Dim notsave As New TaskDialogCommandLink("notsave", "Aufträge verwerfen" + Constants.vbLf + "Nicht gespeicherte Änderungen gehen verloren!")
                    AddHandler notsave.Click, AddressOf notsave_Click
                    Dim abort As New TaskDialogCommandLink("abort", "Abbrechen" + Constants.vbLf + "Die Firma wird nicht gewechselt.")
                    AddHandler abort.Click, AddressOf abort_Click

                    td.Controls.Add(saveandmark)
                    td.Controls.Add(save)
                    td.Controls.Add(notsave)
                    td.Controls.Add(abort)
                    td.Show()
                Else
                    PSTaskDialog.cTaskDialog.ForceEmulationMode = True
                    PSTaskDialog.cTaskDialog.EmulatedFormWidth = 450
                    Select Case PSTaskDialog.cTaskDialog.ShowCommandBox("Aufträge merken", "Aufträge beim nächsten Start anzeigen?", "Sie haben noch einen oder mehrere Aufträge geöffnet. Wählen Sie eine der unteren Aktionen:", "Aufträge speichern und merken|Aufträge speichern|Aufträge verwerfen|Abbrechen", False)
                        Case 0
                            saveandmark_Click(Nothing, Nothing)
                        Case 1
                            save_Click(Nothing, Nothing)
                        Case 2
                            notsave_Click(Nothing, Nothing)
                        Case 3
                            abort_Click(Nothing, Nothing)
                    End Select
                End If
            End If

            If abortcompanychange = False Then
                Dim titem As TabItem = BackStageFirmenWahl.SelectedItem
                loader.LastCompany = titem.Header
                isloading = True
                RibbonWindow_Loaded(Nothing, Nothing)
                RaiseEvent CompanyChanged()
            End If
        End If
    End Sub

    Private Sub BSButton1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles BSButton1.Click
        Dim a1 As New Address
        a1.No = BSTextBox3.Text
        a1.Street = BSTextBox2.Text
        a1.City = BSTextBox5.Text
        a1.ZipCode = BSTextBox4.Text
        Try
            IO.Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory() + "\Firma\" + BSTextBox1.Text)
        Catch ex As Exception
            MessageBox.Show("Kann die Firma nicht erstellen, da bereits ein Ordner mit dem selben Namen existiert oder der Firmenname unzulässige Zeichen enthält.", "Fehler beim Anlegen der Firma", MessageBoxButton.OK, MessageBoxImage.Error)
            Exit Sub
        End Try
        loader.LastCompany = BSTextBox1.Text
        loader.ReloadAllDatabases()
        Dim cs As New nHibernate.Models.CompanySettingsModel
        cs.CompanyName = BSTextBox1.Text
        cs.TaxID = BSTextBox7.Text
        cs.TradeID = BSTextBox6.Text
        cs.FromAddress(a1)
        loader.SaveOrUpdateCompanySettings(cs)
        LoadBackstage()
        If CheckBox1.IsChecked Then
            _ribbon.SelectedTabItem = TabVerwaltung
            TabControl1.SelectedItem = TabItem8
        End If
    End Sub
#Region "Firmendaten"
    ''' <summary>
    ''' Shows the Normal Grid and Save Changes
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub BScButton1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles BScButton1.Click
        'Speichern
        Dim a1 As New Address
        a1.No = BScTextBox3.Text
        a1.Street = BScTextBox2.Text
        a1.City = BScTextBox5.Text
        a1.ZipCode = BScTextBox4.Text

        Dim cs As New nHibernate.Models.CompanySettingsModel With {.TaxID = BScTextBox7.Text, .TradeID = BScTextBox6.Text, .CompanyName = loader.LastCompany}
        cs.FromAddress(a1)
        loader.SaveOrUpdateCompanySettings(cs)

        'Ansicht aktualisieren
        loader.ReloadCompanySettings()
        Label112.Content = cs.TaxID
        Label111.Content = cs.TradeID
        Label108.Content = loader.LastCompany
        Label109.Content = a1.Street + " " + a1.No
        Label110.Content = a1.ZipCode + " " + a1.City

    End Sub
#End Region

    Private Sub Button6_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button6.Click
        'Bugs
        Process.Start("http://biller.codeplex.com/workitem/list/basic")
    End Sub

    Private Sub Button7_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button7.Click
        Process.Start("http://www.amazon.de/registry/wishlist/803LODP214HV")
    End Sub
#End Region

#Region "Update"
    Private Sub NewUpdate(ByVal file As UpdateFileInfo, ByVal newVersion As Decimal) Handles UpdateChecker.Update
        Dim updateitem As TabItem
        UpdateContextGroup.Dispatcher.Invoke(Sub()
                                                 UpdateContextGroup.Visibility = Windows.Visibility.Visible
                                             End Sub)
        'updatelist.Add(file)
        updateitem = New TabItem
        updateitem.Header = file.Description + " (Update auf Version " + New String(newVersion.ToString).Replace(",", ".") + ")"

        Dim ucontrol As New UpdateControl(file, UpdateChecker)

        ucontrol.Margin = New Thickness(0)
        updateitem.Content = ucontrol
        UpdateControl.Items.Dispatcher.Invoke(Sub()
                                                  UpdateControl.Items.Add(updateitem)
                                              End Sub)

    End Sub

    Private Sub UpdateSuccessfull(file As UpdateFileInfo) Handles UpdateChecker.Updated
        If TaskDialog.IsPlatformSupported Then
            Dim td As New TaskDialog()
            td.Cancelable = True
            td.Icon = TaskDialogStandardIcon.Information
            td.Caption = "Update erfolgreich installiert"
            td.InstructionText = "Das Update wurde erfolgreich installiert."
            td.Text = "Möglicherweise wird die neue Funktionsweise erst nach einem Neustart des Programms aktiviert."
            td.StandardButtons = TaskDialogStandardButtons.Ok
            td.Show()
        Else
            PSTaskDialog.cTaskDialog.ForceEmulationMode = True
            PSTaskDialog.cTaskDialog.EmulatedFormWidth = 450
            PSTaskDialog.cTaskDialog.MessageBox("Update erfolgreich installiert", "Das Update wurde erfolgreich installiert.", "Möglicherweise wird die neue Funktionsweise erst nach einem Neustart des Programms aktiviert.", PSTaskDialog.eTaskDialogButtons.OK, PSTaskDialog.eSysIcons.Information)
        End If
        For Each Tab As TabItem In UpdateControl.Items
            Try
                Dim c As UpdateControl = Tab.Content
                If c._file.Filename = file.Filename Then
                    UpdateControl.Items.Remove(Tab)
                    If UpdateControl.Items.Count <= 2 Then
                        _ribbon.SelectedTabItem = TabAuftrag
                        UpdateContextGroup.Visibility = Windows.Visibility.Collapsed
                    End If
                    Exit Sub
                End If
            Catch ex As Exception : End Try
        Next
    End Sub

    Private Sub CloseApplication() Handles UpdateChecker.CloseApplication
        Application.Current.Shutdown()
    End Sub

    Private Sub RefreshAddins() Handles UpdateChecker.ReloadAddins
        addinmanager = New AddInManager(Dispatcher, Me, CurrentUser)
        ListView3.DataContext = addinmanager.AddInList
        RegisterLayout()
    End Sub
#End Region

#Region "Sortieren"
    Private Sub ListView1ColumnHeaderClickedHandler(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim headerClicked As GridViewColumnHeader = TryCast(e.OriginalSource, GridViewColumnHeader)
        If headerClicked IsNot Nothing Then
            If headerClicked.Role <> GridViewColumnHeaderRole.Padding Then
                Dim header As String = TryCast(headerClicked.Column.Header, String)
                Select Case header
                    Case GetUIString("date")
                        ordervm.SortByDate()
                    Case GetUIString("type")
                        ordervm.SortByType()
                    Case GetUIString("number")
                        ordervm.SortByID()
                    Case GetUIString("name")
                        ordervm.SortByCustomer()
                    Case GetUIString("amount")
                        ordervm.SortByValue()
                End Select
            End If
        End If
    End Sub

    Private Sub ListView2ColumnHeaderClickedHandler(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim headerClicked As GridViewColumnHeader = TryCast(e.OriginalSource, GridViewColumnHeader)
        If headerClicked IsNot Nothing Then
            If headerClicked.Role <> GridViewColumnHeaderRole.Padding Then
                Dim header As String = TryCast(headerClicked.Column.Header, String)
                Select Case header
                    Case GetUIString("articlenumber")
                        articlevm.SortByID()
                    Case GetUIString("articledescription")
                        articlevm.SortByDescription()
                    Case GetUIString("price")
                        articlevm.SortByPrice()
                    Case GetUIString("unit")
                        articlevm.SortByUnit()
                End Select
            End If
        End If
    End Sub

    Private Sub ListView3ColumnHeaderClickedHandler(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim headerClicked As GridViewColumnHeader = TryCast(e.OriginalSource, GridViewColumnHeader)
        If headerClicked IsNot Nothing Then
            If headerClicked.Role <> GridViewColumnHeaderRole.Padding Then
                Dim header As String = TryCast(headerClicked.Column.Header, String)
                Select Case header
                    Case GetUIString("customerno")
                        customervm.SortByID()
                    Case GetUIString("customername")
                        customervm.SortByName()
                    Case GetUIString("address")
                        customervm.SortByAddress()
                End Select
            End If
        End If

    End Sub
#End Region

#Region "Sichern und Wiederherstellen"
    Private backuplist As New Collection(Of KeyValuePairs)
    Private Sub ButtonSichern_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonSichern.Click
        AddBackupEntry(loader.Backup)
    End Sub

    Private Sub ButtonWiederherstellen_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonWiederherstellen.Click
        ' Configure open file dialog box
        If loader.Restore() Then
            RibbonWindow_Loaded(Nothing, Nothing)
            RaiseEvent CompanyChanged()
        End If
    End Sub

    Private Sub AddBackupEntry(ByVal pathtobackup As String)
        Dim path As String = System.AppDomain.CurrentDomain.BaseDirectory() + "\backuplist.xml"
        If Not IO.File.Exists(path) Then
            Dim fn As New IO.StreamWriter(IO.File.Open(path, IO.FileMode.Create))
            fn.WriteLine("<?xml version=""1.0"" encoding=""utf-8""?>")
            fn.WriteLine("<backuplist>")
            fn.WriteLine("</backuplist>")
            fn.Close() 'all done
        End If
        Dim xd As New XmlDocument
        xd.Load(path)
        Dim root As XmlElement = xd.DocumentElement.SelectSingleNode("/backuplist")
        Dim nodeList As XmlNodeList = root.GetElementsByTagName("backup")
        If nodeList.Count > 5 Then
            root.RemoveChild(root.FirstChild)
        End If
        Dim list As IEnumerator = nodeList.GetEnumerator
        While list.MoveNext
            Dim item As XmlElement = list.Current
            If item.Attributes.GetNamedItem("Path").Value.ToString = pathtobackup Then
                root.RemoveChild(item)
                xd.Save(path)
                AddBackupEntry(pathtobackup)
                Exit Sub
            End If
        End While
        Dim node As XmlElement = xd.CreateElement("backup")
        node.SetAttribute("Date", New Datum(Date.Today).ToString)
        node.SetAttribute("Path", pathtobackup)
        root.AppendChild(node)
        xd.Save(path)
        FillBackupListView()
    End Sub

    Private Sub FillBackupListView()
        backuplist.Clear()
        Dim path As String = System.AppDomain.CurrentDomain.BaseDirectory() + "\backuplist.xml"
        If Not IO.File.Exists(path) Then
            Dim fn As New IO.StreamWriter(IO.File.Open(path, IO.FileMode.Create))
            fn.WriteLine("<?xml version=""1.0"" encoding=""utf-8""?>")
            fn.WriteLine("<backuplist>")
            fn.WriteLine("</backuplist>")
            fn.Close() 'all done
        End If
        Dim xd As New XmlDocument
        xd.Load(path)
        Dim root As XmlElement = xd.DocumentElement.SelectSingleNode("/backuplist")
        Dim nodeList As XmlNodeList = root.GetElementsByTagName("backup")
        Dim list As IEnumerator = nodeList.GetEnumerator
        'Dim kvp As New Collection(Of KeyValuePairs)
        Try
            While list.MoveNext
                Dim node As XmlElement = list.Current
                If IO.File.Exists(node.Attributes.GetNamedItem("Path").Value.ToString) Then
                    Dim litem As New TabItem
                    litem.Header = "Sicherung vom " + node.Attributes.GetNamedItem("Date").Value.ToString
                    backuplist.Add(New KeyValuePairs(node.Attributes.GetNamedItem("Path").Value.ToString, node.Attributes.GetNamedItem("Date").Value.ToString))
                    TabControlLastSaves.Items.Add(litem)
                End If
            End While
        Catch ex As Exception
            'STA Thread
        End Try
    End Sub

    Private Sub TabControlLastSaves_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles TabControlLastSaves.SelectionChanged
        If TypeOf TabControlLastSaves.SelectedItem Is KeyValuePairs AndAlso selectable Then
            Dim item As KeyValuePairs = TabControlLastSaves.SelectedItem
            Dim backup As New BackupAndRestore(System.AppDomain.CurrentDomain.BaseDirectory() + "Firma")
            If IO.File.Exists(item.Key) Then
                ProgressBar4.Visibility = Windows.Visibility.Visible
                ProgressBar4.IsIndeterminate = True
                Dim path As String = item.Key
                Dim t1 As New Thread(Sub()
                                         backup.Wiederherstellen(path)
                                     End Sub)
                t1.Start()
                t1.Join()
                isloading = True
                RibbonWindow_Loaded(Nothing, Nothing)
                RaiseEvent CompanyChanged()
                ProgressBar4.IsIndeterminate = False
                ProgressBar4.Value = 100
                Exit Sub
            Else
                MessageBox.Show("Datei nicht mehr vorhanden. Bitte wählen sie eine Andere!", "Andere Datei wählen", MessageBoxButton.OK, MessageBoxImage.Error)
                TabControlLastSaves.Items.Remove(TabControlLastSaves.SelectedItem)
                Exit Sub
            End If
        End If
    End Sub

    Private Sub TabControlLastSaves_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles TabControlLastSaves.Loaded
        TabControlLastSaves.SelectedIndex = -1
    End Sub

    Private Sub TabControlLastSaves_PreviewMouseDown(sender As System.Object, e As System.Windows.Input.MouseButtonEventArgs) Handles TabControlLastSaves.PreviewMouseDown
        selectable = True
    End Sub

    Private Sub TabControlLastSaves_PreviewMouseUp(sender As System.Object, e As System.Windows.Input.MouseButtonEventArgs) Handles TabControlLastSaves.PreviewMouseUp
        selectable = False
    End Sub

    Private selectable As Boolean = False
    Private Property BackUpDirectory As String
        Get
            Dim temp As String = loader.GetSettingByKey("AutoBackupPath")
            If String.IsNullOrWhiteSpace(temp) Then
                Return System.AppDomain.CurrentDomain.BaseDirectory() + "Backups"
            Else
                Return temp
            End If
        End Get
        Set(value As String)
            loader.SetSettingByKey("AutoBackupPath", value)
        End Set
    End Property

    Private Sub AutomaticBackup()
        If ToggleButton4.IsChecked Then
            If IO.Directory.Exists(BackUpDirectory) = False Then
                IO.Directory.CreateDirectory(BackUpDirectory)
            End If
            Dim backup As New BackupAndRestore(System.AppDomain.CurrentDomain.BaseDirectory() + "Firma")
            Dim t1 As New Thread(Sub()
                                     backup.Backup(BackUpDirectory + "\backup " + DateTime.Now.ToString().Replace(":", "-") + ".zip")
                                     AddBackupEntry(BackUpDirectory + "\backup " + DateTime.Now.ToString().Replace(":", "-") + ".zip")
                                 End Sub)
            t1.Start()
        End If
    End Sub
#End Region

#Region "AddIns"
#Region "Browser"
    WithEvents downloader As New FileDownloader
    Private downloadedfilename As String
    Private Sub ListViewAddIn_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles ListViewAddIn.SelectionChanged
        If ListViewAddIn.SelectedItems.Count > 0 Then
            Dim current As DataRowView = ListViewAddIn.SelectedItem
            TextBlock7.Text = current("Info")
            Button14.IsEnabled = True
        Else
            Button14.IsEnabled = False
        End If
    End Sub

    Private Sub Button14_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button14.Click
        Dim current As DataRowView = ListViewAddIn.SelectedItem
        Dim fileinfo As New FileDownloader.FileInfo(current("Path"))
        downloadedfilename = fileinfo.Name
        downloader.Files.Clear()
        downloader.Files.Add(fileinfo)
        downloader.LocalDirectory = My.Computer.FileSystem.SpecialDirectories.Temp
        downloader.Start()
    End Sub

    Private Sub downloader_progress() Handles downloader.ProgressChanged
        ProgressBar2.Value = downloader.CurrentFilePercentage()
    End Sub

    Private Sub downloader_StateChanged() Handles downloader.StateChanged
        If downloader.IsBusy = False Then
            Dim pro As New Process()
            pro.StartInfo.FileName = My.Computer.FileSystem.SpecialDirectories.Temp + "\" + downloadedfilename
            pro.StartInfo.Arguments = "/S /D=" + System.AppDomain.CurrentDomain.BaseDirectory()
            pro.Start()
            pro.WaitForExit()
            Try
                IO.File.Delete(My.Computer.FileSystem.SpecialDirectories.Temp + "\" + downloadedfilename)
            Catch ex As Exception : End Try
            RefreshAddins()
            TextBlock7.Text = "Erweiterung installiert"
            GenerateAddInList()
        End If
    End Sub

    Private Sub GenerateAddInList()
        Dim xd As New Xml.XmlDocument
        Try
            Dim t1 As Task = Task.Factory.StartNew(Sub()
                                                       Try
                                                           xd.Load("http://www.lastelb.com/biller/update/addinlist.xml")
                                                           Dim root As Xml.XmlElement = xd.DocumentElement
                                                           Dim nodeList As XmlNodeList = root.GetElementsByTagName("AddIn")
                                                           Dim list As IEnumerator = nodeList.GetEnumerator
                                                           Dim element As XmlElement
                                                           Dim tbl As New DataTable
                                                           tbl.Columns.Add("Name")
                                                           tbl.Columns.Add("Size")
                                                           tbl.Columns.Add("Info")
                                                           tbl.Columns.Add("Path")
                                                           Do While (list.MoveNext())
                                                               element = CType(list.Current, XmlElement)
                                                               With element.Attributes
                                                                   Dim fileinfo As New FileDownloader.FileInfo(.GetNamedItem("Path").Value.ToString)
                                                                   If IO.File.Exists(System.AppDomain.CurrentDomain.BaseDirectory() + "\" + .GetNamedItem("MainFile").Value.ToString) = False Then
                                                                       Try
                                                                           If (CDec(.GetNamedItem("RequiredVersion").Value) > Version) Then
                                                                               tbl.Rows.Add(.GetNamedItem("Name").Value, .GetNamedItem("Size").Value, .GetNamedItem("Info").Value, .GetNamedItem("Path").Value)
                                                                           End If
                                                                       Catch ex As Exception : End Try
                                                                   End If
                                                               End With
                                                           Loop
                                                           ListViewAddIn.Dispatcher.Invoke(Sub()
                                                                                               ListViewAddIn.DataContext = tbl
                                                                                           End Sub)
                                                       Catch ex As Exception

                                                       End Try

                                                   End Sub)

        Catch ex As Exception : End Try
    End Sub
#End Region
#End Region

    Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
        BackStageMenu.IsOpen = False
        _ribbon.SelectedTabItem = TabVerwaltung
        SettingsTabControl.SelectedItem = TabItemV3
    End Sub

    Public Function GetUIString(key As String) As String
        Try
            Return FindResource(key)
        Catch ex As Exception
            Return key
        End Try
    End Function

    Private Sub Button15_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button15.Click
        'Translation
        Process.Start("http://biller.codeplex.com/discussions")
    End Sub

    Private Sub FocusTBParentForMVVM(textbox As TextBox)
        Dim ancestor As DependencyObject = textbox.Parent
        While ancestor IsNot Nothing
            Dim element = TryCast(ancestor, UIElement)
            If element IsNot Nothing AndAlso element.Focusable Then
                element.Focus()
                Exit While
            End If
            ancestor = VisualTreeHelper.GetParent(ancestor)
        End While
    End Sub

#Region "FlyOuts"
    Private Sub ShowFlyOuts()
        Dim sb As Storyboard = FindResource("ShowFlyOuts")
        sb.Begin(Me)
    End Sub

    Private Sub HideFlyOuts()
        Dim sb As Storyboard = FindResource("HideFlyOuts")
        Dim anim As DoubleAnimationUsingKeyFrames = sb.Children(0)
        Dim kf As EasingDoubleKeyFrame = anim.KeyFrames(0)
        kf.Value = FlyOutRight.ActualWidth

        Dim anim2 As DoubleAnimationUsingKeyFrames = sb.Children(1)
        Dim kf2 As EasingDoubleKeyFrame = anim2.KeyFrames(0)
        kf2.Value = -FlyOutLeft.ActualWidth
        sb.Begin(Me)
    End Sub

    Private x As Integer = -1
    Private Sub FlyOuts_MouseDown(sender As System.Object, e As System.Windows.Input.MouseButtonEventArgs) Handles FlyOuts.MouseDown
        If NewCompany.Visibility = Windows.Visibility.Collapsed Then
            x = Mouse.GetPosition(Me).X
        End If
    End Sub

    Private Sub FlyOuts_MouseUp(sender As System.Object, e As System.Windows.Input.MouseButtonEventArgs) Handles FlyOuts.MouseUp
        x = -1
    End Sub

    Private Sub FlyOuts_MouseMove(sender As System.Object, e As System.Windows.Input.MouseEventArgs) Handles FlyOuts.MouseMove
        If Math.Abs(Mouse.GetPosition(Me).X - x) > (Me.Width / 10) AndAlso x <> -1 AndAlso NewCompany.Visibility = Windows.Visibility.Collapsed AndAlso CurrentUser IsNot Nothing Then
            HideFlyOuts()
            x = -1
        End If
    End Sub

    ''' <summary>
    ''' QA New Order
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Tile1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Tile1.Click
        If CurrentUser IsNot Nothing Then
            buttonNeuerAuftrag_Click(Nothing, Nothing)
            HideFlyOuts()
        End If
    End Sub

    ''' <summary>
    ''' QA Artikel
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Tile2_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Tile2.Click
        If CurrentUser IsNot Nothing Then
            _ribbon.SelectedTabItem = TabArtikel
            HideFlyOuts()
        End If
    End Sub

    ''' <summary>
    ''' QA Kunde
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Tile3_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Tile3.Click
        If CurrentUser IsNot Nothing Then
            _ribbon.SelectedTabItem = TabKunde
            HideFlyOuts()
        End If
    End Sub

    Private Sub FlyOuts_TouchDown(sender As System.Object, e As System.Windows.Input.TouchEventArgs) Handles FlyOuts.TouchDown
        If NewCompany.Visibility = Windows.Visibility.Collapsed Then
            x = e.GetTouchPoint(Me).Position.X
        End If
    End Sub

    Private Sub FlyOuts_TouchMove(sender As System.Object, e As System.Windows.Input.TouchEventArgs) Handles FlyOuts.TouchMove
        If Math.Abs(e.GetTouchPoint(Me).Position.X - x) > (Me.Width / 10) AndAlso x <> -1 AndAlso NewCompany.Visibility = Windows.Visibility.Collapsed AndAlso CurrentUser IsNot Nothing Then
            HideFlyOuts()
            x = -1
        End If
    End Sub

    Private Sub FlyOuts_TouchUp(sender As System.Object, e As System.Windows.Input.TouchEventArgs) Handles FlyOuts.TouchUp
        x = -1
    End Sub

    'Private Sub NewCompanyResume_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles NewCompanyResume.Click
    '    Dim a1 As New Address
    '    a1.Street = NewCompanyStreet.Text
    '    a1.No = NewCompanyNo.Text
    '    a1.ZipCode = NewCompanyZip.Text
    '    a1.City = NewCompanyCity.Text
    '    Try
    '        IO.Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory() + "\Firma\" + NewCompanyName.Text)
    '    Catch ex As Exception
    '        MessageBox.Show("Kann die Firma nicht erstellen, da bereits ein Ordner mit dem selben Namen existiert oder der Firmenname unzulässige Zeichen enthält.", "Fehler beim Anlegen der Firma", MessageBoxButton.OK, MessageBoxImage.Error)
    '        Exit Sub
    '    End Try
    '    Dim cs As New nHibernate.Models.CompanySettingsModel
    '    cs.CompanyName = NewCompanyName.Text
    '    cs.FromAddress(a1)
    '    loader.SaveOrUpdateCompanySettings(cs)
    '    loader.LastCompany = NewCompanyName.Text
    '    loader.ReloadAllDatabases()

    '    Try
    '        loader.SaveOrUpdateUnit(New Unit With {.Name = "Kilogramm", .ShortName = "Kg"})
    '        loader.SaveOrUpdateUnit(New Unit With {.Name = "Flasche(n)", .ShortName = "Fl"})
    '        loader.SaveOrUpdateUnit(New Unit With {.Name = "Stück", .ShortName = "St"})
    '        loader.SaveOrUpdateUnit(New Unit With {.Name = "Beutel", .ShortName = "Btl"})
    '        loader.SaveOrUpdateUnit(New Unit With {.Name = "Schale", .ShortName = "Sch"})
    '        loader.SaveOrUpdateUnit(New Unit With {.Name = "Kiste", .ShortName = "Ki"})
    '        loader.SaveOrUpdateUnit(New Unit With {.Name = "Meter", .ShortName = "m"})
    '        loader.SaveOrUpdateUnit(New Unit With {.Name = "Stunde(n)", .ShortName = "h"})
    '        loader.SaveOrUpdateUnit(New Unit With {.Name = "Glas", .ShortName = "Gl"})
    '        loader.SaveOrUpdateUnit(New Unit With {.Name = "Paket", .ShortName = "Pa"})
    '        loader.SaveOrUpdateUnit(New Unit With {.Name = "Liter", .ShortName = "Ltr"})

    '        loader.SaveOrUpdateTax(New TaxClass With {.Name = "MwSt. 19%", .TaxRate = 19})
    '        loader.SaveOrUpdateTax(New TaxClass With {.Name = "MwSt. 7%", .TaxRate = 7})
    '    Catch ex As Exception

    '    End Try

    '    For Each a In Article.GenerateSampleArticles(loader)
    '        articlevm.SaveArticle(a)
    '    Next
    '    For Each c In Customer.GenerateSampleCustomers(loader)
    '        customervm.SaveCustomer(c)
    '    Next
    '    If ToggleImport.IsChecked Then
    '        GoToImport = True
    '    End If
    '    NewCompany.Visibility = Windows.Visibility.Collapsed
    '    WelcomeRight.Visibility = Windows.Visibility.Visible
    '    SPWelcomeLeft.Visibility = Windows.Visibility.Visible
    'End Sub
#End Region

    Protected Sub NotifyPropertyChanged(info As [String])
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
    End Sub

    Public Event PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged

#Region "Stats Contextgroup"
    Private statscomingfrom As Fluent.RibbonTabItem

    Private Sub StatsPDF_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles StatsPDF.Click
        Select Case statscomingfrom.Name
            Case TabKunde.Name
                Dim dlg As New System.Windows.Forms.SaveFileDialog()
                dlg.Title = "Statistik als PDF Speichern"
                dlg.DefaultExt = ".pdf" ' Default file extension
                dlg.Filter = "PDF-Datei |*.pdf" ' Filter files by extension
                If dlg.ShowDialog() = Windows.Forms.DialogResult.OK Then
                    Dim c As Collection(Of FuncClasses.Statistics.CustomerValueModel) = LVCustomerSalesList.ItemsSource
                    Dim t As List(Of FuncClasses.Statistics.CustomerValueModel) = c.ToList
                    Dim header As New Collection(Of String)
                    header.Add("Kundennummer") : header.Add("Kunde") : header.Add("Umsatz") : header.Add("Prozent am Gesamtumsatz")
                    Dim widths As New Collection(Of Single)
                    widths.Add(1) : widths.Add(2) : widths.Add(1) : widths.Add(1)
                    Dim content As New Collection(Of String)
                    For Each item In t
                        content.Add(item.CustomerID)
                        content.Add(item.CustomerName)
                        content.Add(item.Value.ToString)
                        content.Add(item.Percent)
                    Next
                    Dim ex As New TablePDFExport()
                    ex.FilePath = dlg.FileName
                    ex.OpenFileAfterCreation = True
                    ex.TableStyle = tablestyle
                    ex.CreateTable("Umsatz aller Kunden vom " + Datum.DateToString(calendarCustomerSalesStart.SelectedDate) + " bis " + Datum.DateToString(calendarCustomerSalesEnd.SelectedDate), header, content, widths)
                End If
            Case TabArtikel.Name
                Dim dlg As New System.Windows.Forms.SaveFileDialog()
                dlg.Title = "Statistik als PDF Speichern"
                dlg.DefaultExt = ".pdf" ' Default file extension
                dlg.Filter = "PDF-Datei |*.pdf" ' Filter files by extension
                If dlg.ShowDialog() = Windows.Forms.DialogResult.OK Then
                    Dim c As Collection(Of FuncClasses.ArticleAmountModel) = LVArticlesSalesList.ItemsSource
                    Dim t As List(Of FuncClasses.ArticleAmountModel) = c.ToList
                    Dim header As New Collection(Of String)
                    header.Add("Artikelnummer") : header.Add("Artikelname") : header.Add("Menge") : header.Add("Umsatz")
                    Dim widths As New Collection(Of Single)
                    widths.Add(1) : widths.Add(2) : widths.Add(1) : widths.Add(1)
                    Dim content As New Collection(Of String)
                    For Each item In t
                        content.Add(item.Article.ArticleID)
                        content.Add(item.Article.ArticleDescription)
                        content.Add(item.AmountString)
                        content.Add(item.Proceeds.ToString)
                    Next
                    Dim ex As New TablePDFExport()
                    ex.FilePath = dlg.FileName
                    ex.OpenFileAfterCreation = True
                    ex.TableStyle = tablestyle
                    ex.CreateTable("Meistverkaufte Artikel vom " + Datum.DateToString(calendarArticleStatsStart.SelectedDate) + " bis " + Datum.DateToString(calendarArticleStatsEnd.SelectedDate), header, content, widths)
                End If
        End Select

    End Sub

    Private Sub StatsPrint_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles StatsPrint.Click
        Select Case statscomingfrom.Name
            Case TabKunde.Name
                Dim c As Collection(Of FuncClasses.Statistics.CustomerValueModel) = LVCustomerSalesList.ItemsSource
                Dim t As List(Of FuncClasses.Statistics.CustomerValueModel) = c.ToList
                Dim header As New Collection(Of String)
                header.Add("Kundennummer") : header.Add("Kunde") : header.Add("Umsatz") : header.Add("Prozent am Gesamtumsatz")
                Dim widths As New Collection(Of Single)
                widths.Add(1) : widths.Add(2) : widths.Add(1) : widths.Add(1)
                Dim content As New Collection(Of String)
                For Each item In t
                    content.Add(item.CustomerID)
                    content.Add(item.CustomerName)
                    content.Add(item.Value.ToString)
                    content.Add(item.Percent)
                Next
                Dim ex As New TablePDFExport()
                ex.FilePath = "temp.pdf"
                ex.OpenFileAfterCreation = True
                ex.TableStyle = tablestyle
                ex.CreateTable("Jahresumsatz aller Kunden vom " + Datum.DateToString(calendarCustomerSalesStart.SelectedDate) + " bis " + Datum.DateToString(calendarCustomerSalesEnd.SelectedDate), header, content, widths)
            Case TabArtikel.Name
                Dim c As Collection(Of FuncClasses.ArticleAmountModel) = LVArticlesSalesList.ItemsSource
                Dim t As List(Of FuncClasses.ArticleAmountModel) = c.ToList
                Dim header As New Collection(Of String)
                header.Add("Artikelnummer") : header.Add("Artikelname") : header.Add("Menge") : header.Add("Umsatz")
                Dim widths As New Collection(Of Single)
                widths.Add(1) : widths.Add(2) : widths.Add(1) : widths.Add(1)
                Dim content As New Collection(Of String)
                For Each item In t
                    content.Add(item.Article.ArticleID)
                    content.Add(item.Article.ArticleDescription)
                    content.Add(item.AmountString)
                    content.Add(item.Proceeds.ToString)
                Next
                Dim ex As New TablePDFExport()
                ex.OpenFileAfterCreation = True
                ex.TableStyle = tablestyle
                ex.CreateTable("Meistverkaufte Artikel vom " + Datum.DateToString(calendarArticleStatsStart.SelectedDate) + " bis " + Datum.DateToString(calendarArticleStatsEnd.SelectedDate), header, content, widths)
        End Select
    End Sub

    Private Sub StatsBack_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles StatsBack.Click
        _ribbon.SelectedTabItem = statscomingfrom
        StatsContextGroup.Visibility = Windows.Visibility.Collapsed
    End Sub

    Private Sub CustomerSalesListCompleted(result As Collection(Of FuncClasses.Statistics.CustomerValueModel))
        LVCustomerSalesList.ItemsSource = result
    End Sub

    Private Sub calendarCustomerSalesStart_SelectedDatesChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles calendarCustomerSalesStart.SelectedDatesChanged
        Try : companystats.GetCustomerSalesListAsync(calendarCustomerSalesStart.SelectedDate, calendarCustomerSalesEnd.SelectedDate)
        Catch ex As Exception : End Try
    End Sub

    Private Sub calendarCustomerSalesEnd_SelectedDatesChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles calendarCustomerSalesEnd.SelectedDatesChanged
        Try : companystats.GetCustomerSalesListAsync(calendarCustomerSalesStart.SelectedDate, calendarCustomerSalesEnd.SelectedDate)
        Catch ex As Exception : End Try
    End Sub

#End Region

    Private Sub ComboBox1_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles ComboBox1.SelectionChanged
        Select Case ComboBox1.SelectedIndex
            Case 0
                tablestyle = TableStyleTemplates.DefaultStyle
            Case 1
                tablestyle = TableStyleTemplates.Gray_White
            Case 2
                tablestyle = TableStyleTemplates.Blue_White
            Case 3
                tablestyle = TableStyleTemplates.LightGreen_White
        End Select
        loader.SetSettingByKey("tablestyle", ComboBox1.SelectedIndex)
    End Sub

#Region "UserManagement"
    Private _currentuser As User
    Private ReadOnly Property CurrentUser As User
        Get
            Return _currentuser
        End Get
    End Property

    Private Sub MissingUserRights(message As String)
        message = "Zur Durchführung der Aktion fehlt ein benötigtes Recht:" + vbCrLf + " - " + message
        If TaskDialog.IsPlatformSupported Then
            Dim td As New TaskDialog()
            td.Cancelable = True
            td.Icon = TaskDialogStandardIcon.Shield
            td.Caption = "Fehlende Rechte"
            td.InstructionText = "Fehlende Rechte"
            td.Text = message
            td.StandardButtons = TaskDialogStandardButtons.Ok
            td.Show()
        Else
            PSTaskDialog.cTaskDialog.ForceEmulationMode = True
            PSTaskDialog.cTaskDialog.EmulatedFormWidth = 450
            PSTaskDialog.cTaskDialog.MessageBox("Fehlende Rechte", "Fehlende Rechte", message, PSTaskDialog.eTaskDialogButtons.OK, PSTaskDialog.eSysIcons.Warning)
        End If
    End Sub
#End Region

#Region "ShowFlyouts"
    Private Sub Button_Click_1(sender As Object, e As RoutedEventArgs)
        ShowFlyOuts()
    End Sub
#End Region
End Class